django - 更新用户时检查电子邮件?
问题描述
在这里,我有两种用于添加和更新用户的表单。注册表单可以正常工作以检查电子邮件是否已经存在,但是在更新用户时它不能正常工作。问题是当我只更新用户名时,它也会显示电子邮件地址已经存在。我想要的是在更新用户时,如果只有用户更改电子邮件地址并且更改的电子邮件地址已经在使用中,那么我想引发验证错误。我该怎么做?
表格.py
class RegisterForm(UserCreationForm):
def check_email(self):
email = self.cleaned_data['email']
if User.objects.filter(email=email).exists():
raise ValidationError('Email Already Exists')
return email
class Meta:
model = User
fields = ['username', "email", "password1", "password2", 'is_superuser', 'is_staff', 'is_active']
class EditRegisterForm(forms.ModelForm):
def check_email(self):
email = self.cleaned_data['email']
email_exists = User.objects.filter(email=email)
if self.instance and self.instance.pk and not email_exists
return email
else:
raise ValidationError('Email already Exists')
class Meta:
model = User
fields = ['username', "email", 'is_superuser','is_staff', 'is_active']
解决方案
这一行:
email_exists = User.objects.filter(email=email)
与当前用户的电子邮件地址匹配,因此会触发“电子邮件已存在”验证错误。
为避免这种情况,只需从查询集中排除当前用户。
email_exists = User.objects.filter(email=email).exclude(pk=self.instance.pk)
推荐阅读
- android - Entity 的 getId() 方法在 DAO_Impl 中生成标签冲突
- .htaccess - 带有查询字符串参数的 Htaccess 301 重定向
- swift - 从收藏视图自动播放下一个音频文件
- python - 在 URL 端点内的烧瓶应用程序中显示小于或等于输入数字的斐波那契数列
- r - 我正在尝试在回归图上绘制置信区间。
- bash - 在时间变量之间运行 bash 脚本
- java - 具有较大值的奇怪 HashSet 行为
- bash - 从 ls /proc 获取所有 PID
- python - 多处理中的 Python asyncio。每个进程一个事件循环
- java - 解析/拆分字符串并将其上传到数据库