代码之家  ›  专栏  ›  技术社区  ›  Kai

密码重置窗体,自己清理方法

  •  1
  • Kai  · 技术社区  · 15 年前

    我想为密码重置窗体编写自己的方法,以便对新密码(长度、字符等)进行一些测试。所以我在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
    

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

    但是我自己的clean方法没有被调用。这有什么问题?

    2 回复  |  直到 15 年前
        1
  •  0
  •   Mermoz ypnos    15 年前

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

    self.cleaned_data['newpassword1']
    

    通过

    self.cleaned_data.get('newpassword1')
    

    对于所有干净的数据集:

    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
    
        2
  •  0
  •   Kai    15 年前

    我发现了错误。这是我的url.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})