在表单中创建mixin以检查密码

时间:2016-11-07 18:47:37

标签: python django django-models django-forms mixins

我有一些患者,医生等模型,然后我使用它们创建基于ModelForm的表单以及一些其他字段:

class CreateClinicForm(forms.ModelForm):
    email = forms.EmailField(required=True)
    name = forms.CharField(max_length=200, required=True)
    specialties = forms.CharField(max_length=100, required=True)
    phone = forms.IntegerField(required=True)

    class Meta:
        model = Clinic
        fields = ('name', 'specialties')

我有这些表格的密码检查,所以使用mixin会很好。 我试图创建这个,但它不起作用。

class PasswordMatchMixin(object):
    password = forms.CharField(max_length=32, required=True)
    password_confirm = forms.CharField(max_length=32, required=True)

def clean_password_confirm(self):
    password = self.cleaned_data.get('password')
    password_confirm = self.cleaned_data.get('password_confirm')
    if password and password != password_confirm:
        raise ValidationError(_("Passwords don't match"))
    return self.password_confirm

当然,之后我将它添加到我的表格中:

class CreateDoctorForm(PasswordMatchMixin, forms.ModelForm) : ...

一些想法或想法?

1 个答案:

答案 0 :(得分:0)

如果您是cleaning fields that rely on each other,则应覆盖clean而不是clean_password

class PasswordMatchMixin(object):
    password = forms.CharField(max_length=32, required=True)
    password_confirm = forms.CharField(max_length=32, required=True)

    def clean(self):
        cleaned_data = super(PasswordMatchMixin, self).clean()
        password = cleaned_data.get('password')
        password_confirm = cleaned_data.get('password_confirm')
        if password and password != password_confirm:
            raise ValidationError(_("Passwords don't match"))
        return cleaned_data

如果您覆盖表单中的clean,请务必致电super(),以便调用PasswordMatchMixin.clean方法。