将 2 个值传递给验证器

问题描述

在 Django 中,我尝试在表单中使用比较密码和确认密码创建验证器,但我不想在干净的方法中进行。我想要我的 docytom 验证器并将他放在小部件 confirm_password 字段中。

我不知道如何将两个值 password 和 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",min. 8 znaków"),validate_test()],'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'}),}

不,我在网站

enter image description here

中有不同的消息

enter image description here

解决方法

您可以在表单中添加 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