自定义表单验证 [英] Custom form validation

查看:174
本文介绍了自定义表单验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a pretty simple form:

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.")

这是如何自定义表单验证完成的?我需要评估电子邮件,目前没有用户使用该电子邮件地址。我还需要评估密码 password_repeat 匹配。我该怎么做呢?

Is this how custom form validation is done? I need to evaluate on email that no users currently exist with that email address. I also need to evaluate that password and password_repeat match. How can I go about doing this?

推荐答案

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

To validate a single field on it's own you can use a clean_FIELDNAME() method in your form, so for email:

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 ):

then for co-dependant fields that rely on each other, you can overwrite the forms clean() method which is run after all the fields (like email above) have been validated individually:

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(),但这似乎是为消息字段的验证方法你的形式似乎不存在。

I'm not sure where you got clean_message() from, but that looks like it is a validation method made for a message field which doesn't seem to exist in your form.

有关详细信息,请阅读:

Have a read through this for more details:

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

这篇关于自定义表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆