Django,更新资料,检查邮箱是否唯一(排除当前用户邮箱)

0 投票
2 回答
2283 浏览
提问于 2025-04-18 00:46

在一个更新个人资料的页面上,有三个输入框。

  • 名字
  • 姓氏
  • 电子邮件地址

我想通过下面的方法来检查输入的电子邮件地址是否是唯一的,也就是说,看看这个邮箱是不是已经被其他用户使用了。但是,当我输入的邮箱(提示信息中显示的)是当前登录用户的邮箱时,我还是收到了一个错误提示,内容是这个邮箱已经在使用中,请换一个

def clean_email(self):
    email = self.cleaned_data.get('email')
    if User.objects.filter(email__iexact=email).exclude(email=email):
        raise forms.ValidationError('This email address is already in use.'
                                    'Please supply a different email address.')
    return email

2 个回答

0

看看这个

class UserCreationEmailForm(UserCreationForm):

email = forms.EmailField()

class Meta:
        model = User
        fields = ('username', 'email')

def clean_email(self):
        # Check that email is not duplicate
        username = self.cleaned_data["username"]
        email = self.cleaned_data["email"]
        users = User.objects.filter(email__iexact=email).exclude(username__iexact=username)
        if users:
            raise forms.ValidationError('A user with that email already exists.')
        return email.lower()
1

我之前也遇到过类似的问题,当时我想更新用户的邮箱。我的问题在于我试图用同一个表单来更新和创建用户。如果你有一个表单是用来检查邮箱是否被使用的,那就不能用它来更新用户,因为这样会出错,就像现在这样。当你要更新的时候,我建议你使用另一个表单(updateUserForm),然后在清理邮箱的函数(clean_email)中,只需要检查新的邮箱是否被其他用户使用,类似于下面这样:

if not User.objects.filter(email=email):
      #Then there is no other users with the new email
      #Do whatever you have to do, return true or update user
else:
     raise forms.ValidationError('This email address is already in use.'
                                    'Please supply a different email address.')

编辑(更新用户信息):

要更改某个用户的邮箱,你需要遵循三个步骤。首先加载用户,然后更改你想要的属性,最后保存:

existing_user = User.objects.get(id=1)  #You have to change this for your query or user    
existing_user.email = 'new@email.com'    
existing_user.save()

显然,没有人应该在使用 'new@email.com'

撰写回答