2015-04-16 93 views
4

我正在嘗試使用生成的密碼和用戶名保存用戶,而且我遇到了一些麻煩。用Django生成密碼保存用戶

我view.py看起來是這樣的:

... 
if request.method == "POST": 

    u = get_username(request.POST.get('first_name', '').lower() + "." + request.POST.get('last_name', '').lower()) 
    p = User.objects.make_random_password(length = 6) 

    form = PrincipalRegistrationForm(request.POST, request.FILES) 

    if form.is_valid(): 

     ... 

     new_user = form.save(uname = u, pword = p) 

     return HttpResponseRedirect("/path/to/site") 
... 

和我forms.py這樣的:

class PrincipalRegistrationForm(UserCreationForm): 

    first_name = forms.CharField(label = 'First name') 
    last_name = forms.CharField(label = 'Last name') 

    school = forms.ModelChoiceField(queryset = School.objects.all()) 
    profile_pic = forms.FileField(required=False) 



    def save(self,commit = True, uname = "unkown", pword = "unknown"): 

     user = super(PrincipalRegistrationForm, self).save(commit = False) 

     user.username = uname 
     user.set_password = make_password(pword) 

     user.first_name = self.cleaned_data['first_name'] 
     user.last_name = self.cleaned_data['last_name'] 


     if commit: 
      user.save() 
     return user 

    def __init__(self, *args, **kwargs): 
      super(PrincipalRegistrationForm, self).__init__(*args, **kwargs) 
      self.fields.pop('username') 
      self.fields.pop('password1') 
      self.fields.pop('password2') 

由輔助函數產生的用戶名,並取得了FNAME和LNAME的並且它會像代碼一樣發送到保存功能,它工作正常(如果我手動輸入密碼)。現在我想要密碼生成並保存爲用戶名,但我有問題。我得到這些錯誤:

Exception Type: KeyError 
Exception Value: u'password1' 
Exception Location: /usr/local/lib/python2.7/dist-packages/django/contrib/auth/forms.py in save, line 121 

感謝您的任何幫助,我欣賞任何關於如何編寫代碼或如果應該改變的東西的意見。

回溯:

Environment: 


Request Method: POST 
Request URL: http://localhost:8000/siteadmin/add/principal 

Django Version: 1.7.5 
Python Version: 2.7.6 
Installed Applications: 
('django.contrib.admin', 
'django.contrib.auth', 
'django.contrib.contenttypes', 
'django.contrib.sessions', 
'django.contrib.messages', 
'django.contrib.staticfiles', 
'app_accounts', 
'app_schools', 
'app_school_subjects') 
Installed Middleware: 
('django.contrib.sessions.middleware.SessionMiddleware', 
'django.middleware.common.CommonMiddleware', 
'django.middleware.csrf.CsrfViewMiddleware', 
'django.contrib.auth.middleware.AuthenticationMiddleware', 
'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 
'django.contrib.messages.middleware.MessageMiddleware', 
'django.middleware.clickjacking.XFrameOptionsMiddleware') 


Traceback: 

    File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 
     111.      response = wrapped_callback(request, *callback_args, **callback_kwargs) 
    File "/path/to/ednevnik/app_accounts/views.py" in add_principal 
     80.    new_user = form.save(uname = u, pword = p) 
    File "/path/to/ednevnik/app_accounts/forms.py" in save 
     64.   user = super(PrincipalRegistrationForm, self).save(commit = False) 
    File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/forms.py" in save 
     121.   user.set_password(self.cleaned_data["password1"]) 

    Exception Type: KeyError at /siteadmin/add/principal 
    Exception Value: u'password1' 

解決:

def save(self, commit = True, uname = "unkown", pword = "unknown"): 
    # Adding this line solved my problem 
    self.cleaned_data['password1'] = pword 

    user = super(PrincipalRegistrationForm, self).save(commit = False) 

    user.username = uname 
    user.first_name = self.cleaned_data['first_name'] 
    user.last_name = self.cleaned_data['last_name'] 

    if commit: 
     user.save() 
    return user 
+0

我看到了一些東西:'user.set_password'是一個函數,需要像這樣調用:'user.set_password(password)'。然後,這不是一個錯誤,但您不需要重寫'save'函數的所有代碼。你應該繼承父類,並在它之前執行你的代碼。 – Paco

+1

只需驗證'self.cleaned_data'中的內容,就沒有'password1' – Paco

+0

就是這樣!在save函數中'user = super(PrincipalRegistrationForm,self).save(commit = False)'行之前添加'self.cleaned_data [「password1」] = pword'之後,一切正常:D Thnaks! –

回答

0

使用class Meta: exclude = ['somefield']和我的方式做正常保存之前改變形式的實例來解決問題。

+0

它引發了同樣的錯誤:( –

+0

沒有字段名爲「password1」,只有「密碼」,所以如果你只排除「密碼」,你會沒事的 –