Richard Knop
Richard Knop

Reputation: 83725

Django Does Not Throw Validation Exception When Email Field Is Not Valid

This is my model:

class User(models.Model):
    email = models.EmailField(db_index=True, unique=True)
    password = models.CharField(max_length=160, blank=True)

This code is not throwing a ValidationError even though email is invalid:

user = User(email='invalid e-mail address', 'password'='password_hash')
user.save()

Why?

Upvotes: 0

Views: 870

Answers (2)

devict
devict

Reputation: 609

Because you have to either use a ModelForm, or override your save method and call the full_clean() method before saving the User.

Source : Django model fields validation

Upvotes: 1

Rohan
Rohan

Reputation: 53366

You need to call .full_clean() method to validate the attributes appropriately. Otherwise, the record will directly stored in DB.

>>> u=User(email="something", username='x', password="p")
>>> u.full_clean()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/django/db/models/base.py", line 824, in full_clean
    raise ValidationError(errors)
ValidationError: {'email': [u'Enter a valid e-mail address.']}

From documentation of full_clean()

Note that full_clean() will not be called automatically when you call your model’s save() method. You’ll need to call it manually when you want to run one-step model validation for your own manually created models.

Upvotes: 5

Related Questions