Emails are not being validated
maszaa opened this issue · comments
Emails are not being validated:
user = get_user_model().objects.create_user(email="notvalidemail", password="password")
print(user) # notvalidemail
validate_email(user.email) # raises ValidationError: ['Enter a valid email address.']
EmailUser is using EmailField for email field and Django documentation says
EmailField
class EmailField(max_length=254, **options)[source]
A CharField that checks that the value is a valid email address. It uses EmailValidator to validate the input.
How is this possible?
Base on Django documentation, full_clean()
should be called before saving objects:
https://docs.djangoproject.com/en/1.11/ref/models/instances/#django.db.models.Model.full_clean
Using Django 1.11.5 and Django Custom User 0.7
The same happens with Django's builtin User:
>>> import django
>>> django.get_version()
'1.11.5'
>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('john', 'notvalidemail', 'password')
>>> print(user)
john
>>> print(user.email)
notvalidemail
Instead, you should probably use a ModelForm to be able to perform this validation automatically. EmailUserCreationForm
is already provided and ready to use:
>>> from custom_user.forms import EmailUserCreationForm
>>> user_form = EmailUserCreationForm({'email': 'notvalidemail', 'password1': 'password', 'password2': 'password'})
>>> user_form.save()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/nova/.local/share/virtualenvs/django-test-ww69Ub0E/lib/python3.6/site-packages/custom_user/forms.py", line 77, in save
user = super(EmailUserCreationForm, self).save(commit=False)
File "/Users/nova/.local/share/virtualenvs/django-test-ww69Ub0E/lib/python3.6/site-packages/django/forms/models.py", line 463, in save
'created' if self.instance._state.adding else 'changed',
ValueError: The User could not be created because the data didn't validate.
>>> user_form.is_valid()
False
>>> user_form.errors
{'email': ['Enter a valid email address.']}
>>> get_user_model().objects.count()
0