phagyrhe
phagyrhe

Reputation: 197

How to raise ValidationError in Django model if email exist

I am trying to raise ValidationError through validators.py or def clean(self) on an email field in the Django model to know if an email exists in the DB.

Below is a brief of my model:

class Profile(models.Model)
   ...
   email = models.EmailField()
   ...

   def __str__(self)
       return self.f_name

I know I can add unique=True to the model field to ensure that, or simply do a cleaned_data in forms, but the solution I want is that of validator.py or def clean(self) in models.py.

Upvotes: 0

Views: 996

Answers (2)

Antheiz
Antheiz

Reputation: 1

In your forms.py add this function to validate user email exist:

def clean_email(self):
    email = self.cleaned_data.get("email")
    if email and self._meta.model.objects.filter(email__iexact=email).exists():
        self._update_errors(
            ValidationError(
                {
                    "email": self.instance.unique_error_message(
                        self._meta.model, ["email"]
                    )
                }
            )
        )
    else:
        return email

Full custom class form look like this:

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ["username", "email", "password1", "password2"]

    def clean_email(self):
        email = self.cleaned_data.get("email")
        if email and self._meta.model.objects.filter(email__iexact=email).exists():
            self._update_errors(
                ValidationError(
                    {
                        "email": self.instance.unique_error_message(
                            self._meta.model, ["email"]
                        )
                    }
                )
            )
        else:
            return email

Upvotes: 0

phagyrhe
phagyrhe

Reputation: 197

For future reference, if anyone comes across the same issue, all thanks to @dirkgroten, I was able to resolve the problem with clean() in my models.py:

def clean(self)
     if Profile.objects.filter(email=self.email).exclude(pk=self.pk).exists():
            raise ValidationError({'email': _('Email already exists.')})

Upvotes: 0

Related Questions