Prithviraj Mitra
Prithviraj Mitra

Reputation: 11812

Checking duplicate email when editing user profile in Django

I am trying to check the duplicate email while I am logged in as a user and editing my own profile.

But when the email entered is the email of current logged in user and I do not want to update my current email then also I am getting a duplicate email error message.

accounts/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)

How can I check if the entered email is a new email and if it is new email then check duplicate function else ignore email field and update other fields.

Any help/suggestion is highly appreciated. Thanks in advance.

Upvotes: 0

Views: 1756

Answers (1)

dirkgroten
dirkgroten

Reputation: 20692

Use the exclude filter after your filter in order to exclude the current logged in user from your query. Documentation here:

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

It does mean however that your view will need to pass the current user to the form, so you should add that as init argument to the form initialisation (so that self.user = user)

Upvotes: 5

Related Questions