dease
dease

Reputation: 3076

Changing user's email address

I am building simple form which allows user to change his basic (first and last name, email) data. I want to be sure that:

I wanted to use ModelForm for this. I've finished with something like:

class UserDataForm(ModelForm):
    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email']

    def clean_email(self):
        cd = self.cleaned_data
        email = cd['email']
        # Not sure how to check is there is an other account which uses this email EXCEPT this particular user account

I need to show validation error message when there is another account which uses same email AND this account isn't owned by user who is filling the form.

I don't know how to achieve this.

Upvotes: 0

Views: 264

Answers (1)

Alex Lisovoy
Alex Lisovoy

Reputation: 6065

Try this:

class UserDataForm(ModelForm):
    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email']

    def clean_email(self):
        cd = self.cleaned_data
        email = cd['email']

        # object is exists and email is not modified, so don't start validation flow
        if self.instance.pk is not None and self.instance.email == email:
            return cd

        # check email is unique or not
        if User.objects.filter(email=value).exists():
            raise forms.ValidationError("Email address {} already exists!".format(value))
        return cd

Look at this question, I think it will be helpful.

Another way try to check email in clean method:

def clean(self):
    cleaned_data = self.cleaned_data

    if 'email' in self.changed_data and User.objects.filter(email=value).exists():
        raise forms.ValidationError("Email address {} already exists!".format(value))

return cleaned_data

Upvotes: 2

Related Questions