密码重置表单,自己的清理方法

时间:2010-08-07 16:51:02

标签: django django-forms

我想编写自己的密码重置表单方法,对新密码(长度,字符,...)进行一些测试。所以我把这个类添加到了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 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

在urls.py中我添加了这个:

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})

但我没有调用我自己的干净方法。这有什么不对吗?

2 个答案:

答案 0 :(得分:0)

这个答案可能看起来很愚蠢,我没有理由,但我遇到了同样的问题,我通过更换

解决了这个问题
self.cleaned_data['newpassword1']

通过

self.cleaned_data.get('newpassword1')

表示所有clean_data集:

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

答案 1 :(得分:0)

我发现了错误。这是我的urls.py中的一个错误。它必须是:

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})

我不知道为什么我仍然有一个密码重置表而不是404.也许有人可以告诉我。我有点担心可能仍然有可能使用标准的重置表单。