[Django UserCreationForm在电子邮件已经存在时引发验证错误
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Django UserCreationForm在电子邮件已经存在时引发验证错误相关的知识,希望对你有一定的参考价值。
[嗨,我是Django的新手。我有一个从UserCreationForm继承的UserRegisterForm。一切正常
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ["username", "email", "password1", "password2"]
现在,如果数据库中已存在电子邮件,则我想在电子邮件输入框附近显示一个标志“电子邮件已存在”。我已经尝试过:
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ["username", "email", "password1", "password2"]
def clean_email(self):
username = self.cleaned_data.get("username")
if User.objects.filter(username=username).exists():
raise forms.ValidationError("Username is not unique")
return username
def clean_username(self):
email = self.cleaned_data.get("email")
if User.objects.filter(email=email).exists():
raise forms.ValidationError("Email is not unique")
return email
没有用。如果有人可以帮助我,我将非常高兴。
答案
切换两个方法名称:
def clean_username(self):
username = self.cleaned_data.get("username")
if User.objects.filter(username=username).exists():
raise forms.ValidationError("Username is not unique")
return username
def clean_email(self):
email = self.cleaned_data.get("email")
if User.objects.filter(email=email).exists():
raise forms.ValidationError("Email is not unique")
return email
以上是关于[Django UserCreationForm在电子邮件已经存在时引发验证错误的主要内容,如果未能解决你的问题,请参考以下文章
[Django UserCreationForm在电子邮件已经存在时引发验证错误