首页 > 解决方案 > 更新用户时检查电子邮件?

问题描述

在这里,我有两种用于添加和更新用户的表单。注册表单可以正常工作以检查电子邮件是否已经存在,但是在更新用户时它不能正常工作。问题是当我只更新用户名时,它也会显示电子邮件地址已经存在。我想要的是在更新用户时,如果只有用户更改电子邮件地址并且更改的电子邮件地址已经在使用中,那么我想引发验证错误。我该怎么做?

表格.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']

标签: djangoauthentication

解决方案


这一行:

email_exists = User.objects.filter(email=email)

与当前用户的电子邮件地址匹配,因此会触发“电子邮件已存在”验证错误。

为避免这种情况,只需从查询集中排除当前用户。

email_exists = User.objects.filter(email=email).exclude(pk=self.instance.pk)

推荐阅读