51

我有一个非常简单的表格:

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匹配。我该怎么做呢?

4

1 回答 1

126

要单独验证单个字段,您可以在表单中使用 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/

于 2011-10-31T00:44:08.993 回答