问题描述
我想在注册表格中添加一个功能,如果数据库中已经有电子邮件,而不是显示消息,即该电子邮件已经注册。 我正在尝试使用以下代码,但这无法正常工作
accounts / forms.py
from django.contrib.auth import get_user_model
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserCreateForm(UserCreationForm):
# email = forms.EmailField()
class Meta:
fields = ["username","email","password1","password2"]
model = get_user_model()
def clean_email(self):
email = self.cleaned_data.get('email')
if email in User.objects.all():
raise forms.ValidationError("This email is already register")
return email
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['username'].label = 'Display Name'
# self.fields['email'].label = 'Email Address'
解决方法
您以错误的方式运行验证,应该是
class UserCreateForm(UserCreationForm):
# rest of your code
def clean_email(self):
email = self.cleaned_data["email"]
if User.objects.filter(email__iexact=email).exists():
raise forms.ValidationError("Only .edu email addresses allowed")
return email
,
在您的UserCreateForm.clean_email
中,您没有检查正确的方式。您正在通过此if email in User.objects.all()
进行检查。这里的email
不是User
对象。 User.objects.all()
返回queryset
个对象中的一个User
个对象。由于email
不是User
的实例,因此条件检查不成功。而是执行以下操作来检查提供的电子邮件是否已经存在用户
def clean_email(self):
email = self.cleaned_data.get('email')
if email.split('.')[-1] != 'edu' :
raise forms.ValidationError("Only .edu email addresses allowed")
if User.objects.filter(email__iexact=email).exists():
raise forms.ValidationError("User with that email already exists")
return email
确保在email
模型中将User
设置为unique
。