我正在构建简单的表单,允许用户更改其基本(名字和姓氏,电子邮件)数据。 我想确定:
我想为此使用ModelForm。我已经完成了类似的事情:
class UserDataForm(ModelForm):
class Meta:
model = User
fields = ['first_name', 'last_name', 'email']
def clean_email(self):
cd = self.cleaned_data
email = cd['email']
# Not sure how to check is there is an other account which uses this email EXCEPT this particular user account
当有另一个使用相同电子邮件的帐户时,我需要显示验证错误消息,并且此帐户不归填写表单的用户所有。
我不知道如何实现这一点。
答案 0 :(得分:2)
试试这个:
class UserDataForm(ModelForm):
class Meta:
model = User
fields = ['first_name', 'last_name', 'email']
def clean_email(self):
cd = self.cleaned_data
email = cd['email']
# object is exists and email is not modified, so don't start validation flow
if self.instance.pk is not None and self.instance.email == email:
return cd
# check email is unique or not
if User.objects.filter(email=value).exists():
raise forms.ValidationError("Email address {} already exists!".format(value))
return cd
看看这个question,我认为这会有所帮助。
另一种尝试以干净方法检查电子邮件的方式:
def clean(self):
cleaned_data = self.cleaned_data
if 'email' in self.changed_data and User.objects.filter(email=value).exists():
raise forms.ValidationError("Email address {} already exists!".format(value))
return cleaned_data