检查电子邮件是否已经存在?

时间:2019-06-13 06:37:25

标签: django authentication

这里我有两种添加和更新用户的表单。注册表单可以很好地检查电子邮件是否已经存在,但是在更新用户时它不能正常工作。问题是当我确实仅更新用户名时说电子邮件地址已经存在。如果只有用户更改电子邮件地址并且更改的电子邮件地址已经在使用中,我想更新用户,那么我想提出验证错误。该怎么办?

  

forms.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']

2 个答案:

答案 0 :(得分:1)

此行:

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

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

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

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

答案 1 :(得分:1)

您需要在此处更改逻辑

if self.instance and self.instance.pk and User.objects.filter(email=email).exists():
    return email