【问题标题】:Django password and password confirmation validationdjango密码和密码确认验证
【发布时间】:2016-08-19 16:51:18
【问题描述】:

我在验证同一表单中的两个字段(密码和密码确认)时遇到了一点问题。

问题是,在使用我创建的方法验证密码后,当我尝试验证密码确认时,我不再有权访问此变量,password = self.cleaned_data['password']'None'

class NewAccountForm(forms.Form):

password =  forms.CharField(widget=forms.PasswordInput(attrs={'class': 'narrow-input', 'required': 'true' }), required=True, help_text='Password must be 8 characters minimum length (with at least 1 lower case, 1 upper case and 1 number).')
password_confirm = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'narrow-input', 'required': 'true' }), required=True, )

def __init__(self, *args, **kwargs):
    super(NewAccountForm, self).__init__(*args, **kwargs)
    self.fields['password'].label = "Password"
    self.fields['password_confirm'].label = "Password Confirmation"

“密码验证”

def clean_password(self):
    validate_password_strength(self.cleaned_data['password'])

第二次验证未正确执行,因为密码 = 'None':

def clean_password_confirm(self):
    password = self.cleaned_data['password']
    password_confirm = self.cleaned_data.get('password_confirm')

    print(password)
    print(password_confirm)
    if password and password_confirm:
        if password != password_confirm:
            raise forms.ValidationError("The two password fields must match.")
    return password_confirm

如果字段密码的输入已经通过第一种方法 (clean_password) 进行了验证,是否有办法将字段密码的输入用作第二次验证 (clean_password_confirm) 的变量?

谢谢。

编辑:更新版本:

def clean(self):
    cleaned_data = super(NewAccountForm, self).clean()
    password = cleaned_data.get('password')

    # check for min length
    min_length = 8
    if len(password) < min_length:
        msg = 'Password must be at least %s characters long.' %(str(min_length))
        self.add_error('password', msg)

    # check for digit
    if sum(c.isdigit() for c in password) < 1:
        msg = 'Password must contain at least 1 number.'
        self.add_error('password', msg)

    # check for uppercase letter
    if not any(c.isupper() for c in password):
        msg = 'Password must contain at least 1 uppercase letter.'
        self.add_error('password', msg)

    # check for lowercase letter
    if not any(c.islower() for c in password):
        msg = 'Password must contain at least 1 lowercase letter.'
        self.add_error('password', msg)

    password_confirm = cleaned_data.get('password_confirm')


    if password and password_confirm:
        if password != password_confirm:
            msg = "The two password fields must match."
            self.add_error('password_confirm', msg)
    return cleaned_data

【问题讨论】:

    标签: python django


    【解决方案1】:

    您可以在clean() 方法中测试多个字段。

    例子:

    def clean(self):
        cleaned_data = super(NewAccountForm, self).clean()
    
        password = cleaned_data.get('password')
        password_confirm = cleaned_data.get('password_confirm ')
    
        if password and password_confirm:
            if password != password_confirm:
                raise forms.ValidationError("The two password fields must match.")
        return cleaned_data
    

    请参阅Cleaning and validating fields that depend on each other 上的文档。

    【讨论】:

    • 感谢您的帮助。阅读文档后,我使用 clean() 重写了该方法。在这些更改之后,我编辑了我的问题以显示我的代码。如果您能提出任何改进建议,我将不胜感激。而且,作为对您回答的建议,我只会将 return 语句修改为“return clean_data”。
    • 感谢您的建议,确实是一个错字。您的新代码有效,对吗?如果没有,请打开一个新问题。
    猜你喜欢
    • 2013-09-18
    • 2017-07-26
    • 1970-01-01
    • 2015-04-03
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    相关资源
    最近更新 更多