I'm using Django 1.9, and EmailValidator
seems to be validating trailing dots in email ids.
faulty_email = '[email protected].'
user.email = faulty_email
user.save()
The above piece of code runs smoothly even though email
is an EmailField
, which has EmailValidator
. The weird thing is, when I run the validation manually, it throws a ValidationError
.
In [1]: from django.core.validators import validate_email
In [2]: faulty_email = '[email protected].'
In [3]: validate_email(faulty_email)
---------------------------------------------------------------------------
ValidationError Traceback (most recent call last)
<ipython-input-3-bdbbd57d5fe1> in <module>()
----> 1 validate_email(faulty_email)
/usr/local/lib/python2.7/dist-packages/django/core/validators.pyc in __call__(self, value)
201 except UnicodeError:
202 pass
--> 203 raise ValidationError(self.message, code=self.code)
204
205 def validate_domain_part(self, domain_part):
ValidationError: [u'Enter a valid email address.']
Does anyone know what the issue is?
When you save()
a model you’re only telling Django to commit the object to the database. It doesn’t validate during save. It will throw database exceptions if the fields don’t have the format expected by the database but an EmailField
is just a charfield in your db. You should always validate your models before saving them:
user.email = faulty_email
try:
user.full_clean()
except ValidationError as e:
print(e)
else:
user.save()
When using a ModelForm
you first validate the form (check form.is_valid()
) then save it.