简体   繁体   English

Django:无法验证UserCreationForm

[英]Django: Not able to validate UserCreationForm

Below is the content of my forms.py 以下是我的forms.py的内容

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class RegistrationForm(UserCreationForm):

    email = forms.EmailField(required=True)
    first_name = forms.CharField(max_length=20, required=True)
    last_name = forms.CharField(max_length=20, required=True)

    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2', 'first_name', 'last_name')

        def save(self, commit=True):
            user = super(UserCreationForm, self).save(commit=False)
            user.email = self.cleaned_data['email']
            user.first_name = self.cleaned_data['first_name']
            user.last_name = self.cleaned_data['last_name']
#validation of email id----------
            email1 = user.email
            (fisrt, second,) = email1.split("@")
            (domain, exn,) = second.split(".")
            if not domain == "tmail":
                raise forms.ValidationError("Domain must be 'tmail'")

            if commit:
                user.save()
            return user

I am able to print form (including fields email, first_name & last_name) & register the user successfully only issue I have is, Its not performing the validation step. 我能够打印表格(包括电子邮件,名字和姓氏字段)并成功注册用户,只有我遇到的问题是,它不执行验证步骤。 (code below the "#validation of email id----------") Even if the domain is other than "tmail" it is accepting it without raising any validation error & then registering the user into database. (“电子邮件ID #validation ----------”下面的代码)即使该域不是“ tmail”,它也将接受该域而不会引起任何验证错误,然后将用户注册到数据库中。 Please help & let me know in case you need more info. 如果您需要更多信息,请帮助并让我知道。

It is too late to validate the email in the save() method. save()方法中验证电子邮件为时已晚。 Django lets you validate individual fields by defining a method clean_<fieldname> . Django允许您通过定义方法clean_<fieldname>验证各个字段。 This will be called when the form is validated. 验证表单后将调用此方法。

def clean_email(self):
    email = self.cleaned_data['email']
    (first, second,) = email1.split("@")
    (domain, exn,) = second.split(".")
    if domain != "tmail":
        raise forms.ValidationError("Domain must be 'tmail'")
    return email 

See the docs on cleaning a specific field attribute for more info. 有关更多信息,请参阅有关清理特定字段属性的文档。

Why are you doing validation in save? 为什么要在保存中进行验证? All validations must happen before save, such that if any exception does comes in save it is most probably bug in your code. 所有验证必须在保存之前进行,这样,如果保存时发生任何异常,则很可能是代码中的错误。 Forms specifically have 'clean' methods especially for this purpose. 表单特别具有“清理”方法,尤其是为此目的。 For specific field validation, you can use "clean_{field_name}". 对于特定的字段验证,可以使用“ clean_ {field_name}”。 Though if your validation depends on multiple fields, you need to use "clean" method. 尽管如果您的验证取决于多个字段,则需要使用“干净”方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM