Python Django,更新配置文件,检查电子邮件是否唯一(不包括登录用户的电子邮件)

Python Django,更新配置文件,检查电子邮件是否唯一(不包括登录用户的电子邮件),python,django,validation,email,Python,Django,Validation,Email,在更新配置文件页面中,有3个字段 名字 姓 电子邮件地址 通过下面的方法,我尝试查看在字段中输入的电子邮件地址是否唯一(其他成员未使用)。但是当输入的电子邮件地址(占位符)是登录用户的当前电子邮件地址时,我仍然收到一个错误,此电子邮件已在使用中。试试另一个 def clean_email(self): email = self.cleaned_data.get('email') if User.objects.filter(email__iexact=email).exclu

在更新配置文件页面中,有3个字段

  • 名字
  • 电子邮件地址
通过下面的方法,我尝试查看在字段中输入的电子邮件地址是否唯一(其他成员未使用)。但是当输入的电子邮件地址(占位符)是登录用户的当前电子邮件地址时,我仍然收到一个错误,此电子邮件已在使用中。试试另一个

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

当我试图更新用户的电子邮件时,我也遇到了类似的问题。我的问题是因为我试图使用相同的表单来更新和创建用户。如果您有一个检查电子邮件是否被使用的表单,您就不能使用它来更新用户,因为它会像现在这样失败。更新时,我建议您使用另一个表单(updateUserForm),然后def clean_电子邮件功能只需检查新电子邮件是否未用于其他用户,如

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.')
编辑(更新用户信息):

要更改某个用户的电子邮件,您必须遵循3个步骤。加载用户,更改所需属性,然后保存:

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“

看看这个

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()

很抱歉回复太晚,但我刚刚回到这个问题上。我有一个单独的表单(updateProfile)。但是仍然使用
def clean_email
在数据库中查找当前用户的电子邮件地址,因此仍然表示
电子邮件已经在使用中。关于这一点有什么想法吗?要更新配置文件,功能是不同的,要更改现有帐户的电子邮件,你必须加载用户,更改电子邮件并保存更新,请查看本文中的“我的版本”。