2015-11-24 157 views
1

崩潰時我使用Django的形式來改變用戶的密碼時,他們忘記了:程序調試時運行正常,但運行通常

#views.py 
def change_forgotten_password(request, key): 
    if request.method == 'GET': 
     form = ChangePasswordForm() 
     return render(request, 'freelancestudent/change_forgotten_password.html', {'form': form}) 
    else: # post 
     form = ChangePasswordForm(request.POST) 
     if form.is_valid(): 
      user = User.objects.get(forgot_password_key=key) 
      user.set_password(form.cleaned_data['password']) 
      user.save() 
      return redirect('/') 

#forms.py 
class ChangePasswordForm(forms.Form): 
    password = forms.CharField(widget=forms.PasswordInput) 
    confirm_password = forms.CharField(widget=forms.PasswordInput) 

    def is_valid(self): 
     if self.cleaned_data['password'] == self.cleaned_data['confirm_password']: 
      return True 

當我通過使用PyCharm的調試器,一切我的代碼步驟作品完全一樣我想要它;如果密碼匹配,則更新所選用戶的密碼。但是,如果我運行它(python manage.py runserver)它呈現的錯誤:在forms.py的一行字:

AttributeError at /change-forgotten-password/wemnj8vvk37yvikf/ 

'ChangePasswordForm' object has no attribute 'cleaned_data' 

if self.cleaned_data['password'] == self.cleaned_data['confirm_password']: 
    ... 
+0

'self.cleaned_data'由驗證檢查填充。但是,你永遠不會調用'super(ChangePasswordForm,self).is_valid()'。您也可能不想重寫'is_valid()',而是重寫'clean()'並引發一個'ValidationError',因爲當前在驗證失敗時不會顯示可顯示的錯誤消息。 – dhke

+0

我在哪裏打電話? – Nanor

+0

在訪問'self.cleaned_data'之前,在您的重寫'is_valid()'中。但請參閱上面的首選方法。 – dhke

回答

1

form.cleaned_dataform.is_valid()填補。你忘了在表單中調用超級實現。

def is_valid(self): 
    return (
     super(ChangePasswordForm, self).is_valid() 
     and self.cleaned_data['password'] == self.cleaned_data['confirm_password'] 
    ) 

但一般情況下,我會勸阻壓倒一切is_valid(),而是覆蓋form.clean()或similiar。正如布蘭登表示,Django的已經這樣做在自己的SetPasswordForm

def clean_new_password2(self): 
    password1 = self.cleaned_data.get('password') 
    password2 = self.cleaned_data.get('confirm_password') 
    if password1 and password2: 
     if password1 != password2: 
      raise forms.ValidationError(
       self.error_messages['password_mismatch'], 
       code='password_mismatch', 
      ) 
    password_validation.validate_password(password2, self.user) 
    return password2 

你可能會去幹,簡單地重新使用現有的ChangePasswordForm,它接受場'old_password''new_password1''new_password2'所以你可能需要調整您的模板。

相關問題