pythonvalidationdjango-modelsdjango-model-field

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.


Solution

  • 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.')})