Search code examples
pythondjangoemailfield

Django EmailField accepts any value (including blank)


Having this Django model:

class Subscriber(models.Model):
    email = models.EmailField(unique=True, blank=False)

I do not face any exceptions when creating a Subscriber with empty email:

>>> Subscriber.objects.create(email='')
<Subscriber: Subscriber object>

Interesting is that for the second time it will raise the IntegrityError:

>>> Subscriber.objects.create(email='')
...
IntegrityError: column email is not unique

So it seems to validate for integrity, but neither for email format nor for blank entries. How do I have the email validated?


Solution

  • The parameter blank is used from the form, it's not enforced at database level

    From the documentation

    Field.blank If True, the field is allowed to be blank. Default is False.

    Note that this is different than null. null is purely database-related, whereas blank is validation-related. If a field has blank=True, form validation will allow entry of an empty value. If a field has blank=False, the field will be required.

    Indeed the validator documentation says that

    Note that validators will not be run automatically when you save a model

    to enforce that you have to use the full_clean() method.

    The error is thrown because you are trying to insert two times the empty string and you have the unique constraint on the field.