Why is checking if two passwords match in Django so complicated?

后端 未结 4 1006
执念已碎
执念已碎 2020-12-24 04:23

Am I doing something wrong, or is this seriously what the developers expect me to write every time I want to check if two fields are the same?

def c         


        
4条回答
  •  -上瘾入骨i
    2020-12-24 05:18

    http://k0001.wordpress.com/2007/11/15/dual-password-field-with-django/


    Edit: found out the way the admin form deals with the problem: http://code.djangoproject.com/svn/django/trunk/django/contrib/auth/forms.py

    class AdminPasswordChangeForm(forms.Form):
        """
        A form used to change the password of a user in the admin interface.
        """
        password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
        password2 = forms.CharField(label=_("Password (again)"), widget=forms.PasswordInput)
    
        def __init__(self, user, *args, **kwargs):
            self.user = user
            super(AdminPasswordChangeForm, self).__init__(*args, **kwargs)
    
        def clean_password2(self):
            password1 = self.cleaned_data.get('password1')
            password2 = self.cleaned_data.get('password2')
            if password1 and password2:
                if password1 != password2:
                    raise forms.ValidationError(_("The two password fields didn't match."))
            return password2
    
        def save(self, commit=True):
            """
            Saves the new password.
            """
            self.user.set_password(self.cleaned_data["password1"])
            if commit:
                self.user.save()
            return self.user
    

提交回复
热议问题