0

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

  • emails still unique across database
  • user can leave his email untouched
  • user can change his email

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.

dease
  • 2,975
  • 13
  • 39
  • 75

1 Answers1

2

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
Community
  • 1
  • 1
Alex Lisovoy
  • 5,767
  • 3
  • 27
  • 28
  • What if user wants to change last name and first name only? Email will stay untouched, but form will not validate (because there is an User object with such email address. – dease Sep 18 '14 at 09:42