I want to write my own method for the password reset form to make some tests about the new password (length, characters,...). So I added this class to my forms.py:
class PasswordResetForm(SetPasswordForm):
def clean(self):
if 'newpassword1' in self.cleaned_data and 'newpassword2' in self.cleaned_data:
if self.cleaned_data['newpassword1'] != self.cleaned_data['newpassword2']:
raise开发者_如何学Python forms.ValidationError(("The two password fields didn't match."))
#here the passwords entered are the same
if len(self.cleaned_data['newpassword1']) < 8:
raise forms.ValidationError(("Your password has to be at least 8 characters long"))
if not re.search('\d+', self.cleaned_data['newpassword1']) or not re.search('([a-zA-Z])+', self.cleaned_data['new password1']):
raise forms.ValidationError(("Your password needs to contain at least one number and one character"))
return self.cleaned_data
and in the urls.py I added this:
url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', django.contrib.auth.views.password_reset_confirm, {'template_name':'registration/password_reset_confirm.html',
'set_password_form': PasswordResetForm})
But my own clean method isn't called. Whats wrong with this?
this answer may look stupid and i don't have the justification but i ran in the same problem and i solved it by replacing the
self.cleaned_data['newpassword1']
by
self.cleaned_data.get('newpassword1')
for all the clean_data set:
class PasswordResetForm(SetPasswordForm):
def clean(self):
cleaned_data = self.cleaned_data
if 'newpassword1' in cleaned_data and 'newpassword2' in cleaned_data:
if cleaned_data.get('newpassword1') != cleaned_data.get('newpassword2'):
raise forms.ValidationError(("The two password fields didn't match."))
if len(cleaned_data.get('newpassword1')) < 8:
raise forms.ValidationError(("Your password has to be at least 8 characters long"))
if not re.search('\d+', cleaned_data.get('newpassword1')) or not re.search('([a-zA-Z])+', cleaned_data.get('new password1')):
raise forms.ValidationError(("Your password needs to contain at least one number and one character"))
return cleaned_data
I found the error. It was a mistake in my urls.py. It needed to be:
url(r'^password/reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',django.contrib.auth.views.password_reset_confirm,{'template_name':'registration/password_reset_confirm.html','set_password_form': PasswordResetForm})
I don't know why I still got an password reset form and not a 404. Maybe someone can tell me. I'm a bit worried that there might still be a possible way to use the standard reset form.
精彩评论