在Django中编辑用户配置文件时检查重复的电子邮件

时间:2017-08-29 18:00:49

标签: python django

当我以用户身份登录并编辑自己的个人资料时,我正在尝试检查重复的电子邮件。

但是当输入的电子邮件是当前登录用户的电子邮件而我不想更新我当前的电子邮件时,我也收到了重复的电子邮件错误消息。

账户/ forms.py

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = models.Profile
        fields = ("organisation", "phone_number")

    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    phone_number = PhoneNumberField(label=_("Phone (Please state your country code eg. +44)"))
    organisation = forms.CharField(max_length=30)
    email = forms.EmailField()


    def __init__(self, *args, **kwargs):
        super(UserProfileForm, self).__init__(*args, **kwargs)
        self.initial['first_name'] = self.instance.user.first_name
        self.initial['last_name'] = self.instance.user.last_name
        self.initial['email'] = self.instance.user.email

    helper = FormHelper()
    helper.layout = Layout(
        Div(
            Field("first_name", wrapper_class="col-sm-6"),
            Field("last_name", wrapper_class="col-sm-6"),
            css_class = "row"
        ),
        Div(
            Field("organisation", wrapper_class="col-sm-6"),
            Field("email", wrapper_class="col-sm-6"),
            css_class = "row"
        ),
        Div(
            Field("phone_number", wrapper_class="col-sm-6"),
            css_class = "row"
        ),
    )

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if email and User.objects.filter(email=email).exists():
            raise forms.ValidationError(u'Please use a different email address.')
            return email

    def save(self, commit=True, *args, **kwargs):
        self.instance.user.first_name = self.cleaned_data['first_name']
        self.instance.user.last_name = self.cleaned_data['last_name']
        self.instance.user.email = self.cleaned_data['email']
        self.instance.user.save()
        return super(UserProfileForm, self).save(commit, *args, **kwargs)

如何检查输入的电子邮件是否是新电子邮件,如果是新电子邮件,请检查重复功能,否则忽略电子邮件字段并更新其他字段。

非常感谢任何帮助/建议。提前谢谢。

1 个答案:

答案 0 :(得分:3)

exclude后使用filter过滤器,以便从查询中排除当前登录用户。文档here

User.objects.filter(email=email).exclude(id=self.user.id)

但这确实意味着您的视图需要将当前用户传递给表单,因此您应该将其作为init参数添加到表单初始化(以便self.user = user