小编典典

自定义表格验证

django

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

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


阅读 502

收藏
2020-04-01

共1个答案

小编典典

要单独验证单个字段,可以在表单中使用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如上)之后运行的forms 方法:

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你的表单中似乎不存在的字段设计的一种验证方法。

2020-04-01