【问题标题】:Pass 2 values to validator将 2 个值传递给验证器
【发布时间】:2021-07-23 05:57:22
【问题描述】:

在 Django 中,我尝试在表单中创建具有比较密码和确认密码的验证器,但我不想在干净的方法中执行此操作。我想要我的 do cystom 验证器并将他放到小部件的 confirm_password 字段中。

我不知道如何将两个值密码和确认密码传递给我的验证器。

def validate_test():
    cleaned_data = super(UserSignUpForm, self).clean()
    password = cleaned_data.get("password")
    confirm_password = cleaned_data.get("confirm_password")
    print(f'password:{password}\nconfirm_password: {confirm_password}')

    if password != confirm_password:
        raise ValidationError(
            _('%(password)s and %(confirm_password)s does not match - test'),
            params={'password': password, 'confirm_password': confirm_password},
        )


class UserSignUpForm(forms.ModelForm):
   
    password = forms.CharField(
        label="Password",
        validators=[MinLengthValidator(8, message="Zbyt krótkie hasło, min. 8 znaków")],
        widget=forms.PasswordInput(attrs={'style':'max-width: 20em; margin:auto', 'autocomplete':'off'}))
    confirm_password = forms.CharField(
        label="Confirm password",
        validators=[MinLengthValidator(8, message="Zbyt krótkie hasło, min. 8 znaków"), validate_test()],
        widget=forms.PasswordInput(attrs={'style':'max-width: 20em; margin:auto', 'autocomplete':'off'}))

    class Meta:
        model = User
        fields = ("username", 'first_name', 'last_name', "password")
        help_texts = {"username": None}
        widgets = {
            'username': forms.TextInput(attrs={'style':'max-width: 20em; margin:auto'}),
            'first_name': forms.TextInput(attrs={'style':'max-width: 20em; margin:auto'}),
            'last_name': forms.TextInput(attrs={'style':'max-width: 20em; margin:auto'}),

        }

不,我在网站 中有不同的消息

【问题讨论】:

    标签: python django passwords customvalidator


    【解决方案1】:

    您可以在表单中添加clean()(Django Docs) 方法:

    class UserSignUpForm(forms.ModelForm):
       
        ...
        
        def clean(self):
            cleaned_data = super().clean()
            password = cleaned_data.get("password")
            confirm_password = cleaned_data.get("confirm_password")
            print(f'password:{password}\nconfirm_password: {confirm_password}')
    
            if password != confirm_password:
                msg = _('%(password)s and %(confirm_password)s does not match - test') % {
                    'password': password, 'confirm_password': confirm_password
                })
                # raise ValidationError(msg)
                # or use add_error()
                self.add_error('password', msg)
                self.add_error('confirm_password', msg)

    Django 也建议:

    我们一次对多个字段执行验证,因此 form 的 clean() 方法是执行此操作的好地方。请注意,我们是 在这里讨论表单上的 clean() 方法,而之前我们 在字段上编写 clean() 方法。重要的是保持 确定验证位置时,字段和表单差异清晰 事物。字段是单个数据点,表单是一个集合 字段。

    另见Cleaning a specific field attribute

    【讨论】:

    • 我不希望它在表单中以干净的方法使用,因为在前面的网站中我有不同的验证消息和小部件中的验证。我在这个外观上编辑帖子。
    • @darek_82,您可以使用self.add_error('password', msg)self.add_error('confirm_password', msg) 向字段添加错误。
    • 是的,就是这样!谢谢你:)
    猜你喜欢
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    • 2020-07-12
    • 2016-04-27
    相关资源
    最近更新 更多