自定义表单验证

时间:2011-10-30 23:48:38

标签: django django-forms django-validation

我有一个非常简单的形式:

from django import forms

class InitialSignupForm(forms.Form):
    email = forms.EmailField()
    password = forms.CharField(max_length=255, widget = forms.PasswordInput)
    password_repeat = forms.CharField(max_length=255, widget = forms.PasswordInput)

    def clean_message(self):
        email = self.clean_data.get('email', '')
        password = self.clean_data.get('password', '')
        password_repeat = self.clean_data.get('password_repeat', '')

        try:
            User.objects.get(email_address = email)
            raise forms.ValidationError("Email taken.")
        except User.DoesNotExist:
            pass

        if password != password_repeat:
            raise forms.ValidationError("The passwords don't match.")

这是自定义表单验证的完成方式吗?我需要在email上评估当前没有用户使用该电子邮件地址。我还需要评估passwordpassword_repeat匹配。我该怎么做呢?

1 个答案:

答案 0 :(得分:104)

要验证单个字段,您可以在表单中使用clean_FIELDNAME()方法,因此对于电子邮件:

def clean_email(self):
    email = self.cleaned_data['email']
    if User.objects.filter(email=email).exists():
        raise ValidationError("Email already exists")
    return email

然后,对于相互依赖的共同依赖字段,您可以覆盖在所有字段(如上面clean())单独验证后运行的表单email方法:

def clean(self):
    form_data = self.cleaned_data
    if form_data['password'] != form_data['password_repeat']:
        self._errors["password"] = ["Password do not match"] # Will raise a error message
        del form_data['password']
    return form_data

我不确定你从哪里得到clean_message(),但看起来这是一个message字段的验证方法,它似乎不存在于你的表单中。

请仔细阅读以获取更多详细信息:

https://docs.djangoproject.com/en/dev/ref/forms/validation/