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']:
...
'self.cleaned_data'由驗證檢查填充。但是,你永遠不會調用'super(ChangePasswordForm,self).is_valid()'。您也可能不想重寫'is_valid()',而是重寫'clean()'並引發一個'ValidationError',因爲當前在驗證失敗時不會顯示可顯示的錯誤消息。 – dhke
我在哪裏打電話? – Nanor
在訪問'self.cleaned_data'之前,在您的重寫'is_valid()'中。但請參閱上面的首選方法。 – dhke