gpt4 book ai didi

python - Django:无法验证 UserCreationForm

转载 作者:太空宇宙 更新时间:2023-11-03 17:28:24 24 4
gpt4 key购买 nike

下面是我的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

我能够打印表单(包括电子邮件、名字和姓氏字段)并成功注册用户,唯一的问题是,它没有执行验证步骤。 (“#validation of email id----------”下面的代码)即使域不是“tmail”,它也会接受它,而不会引发任何验证错误,然后将用户注册到数据库中。如果您需要更多信息,请帮助并告诉我。

最佳答案

现在验证 save() 中的电子邮件为时已晚。方法。 Django 允许您通过定义方法来验证各个字段clean_<fieldname> 。验证表单时将调用此函数。

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

请参阅 cleaning a specific field attribute 上的文档了解更多信息。

关于python - Django:无法验证 UserCreationForm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32244135/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com