1👍
To validate model fields, do not save the instance directly.
Run clean_fields()
and/or full_clean()
on model before saving.
>>> u = User(username='foo', password='bar', email='foobar')
>>> u
<User: foo>
>>> u.clean_fields()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/vikas/.virtualenvs/venv/lib/python3.4/site-packages/django/db/models/base.py", line 1161, in clean_fields
raise ValidationError(errors)
django.core.exceptions.ValidationError: {'email': ['Enter a valid email address.']}
>>> u.full_clean()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/vikas/.virtualenvs/venv/lib/python3.4/site-packages/django/db/models/base.py", line 1136, in full_clean
raise ValidationError(errors)
django.core.exceptions.ValidationError: {'email': ['Enter a valid email address.']}
>>>
Read about Model field validation @ django-docs
Also, it is a very bad idea to save user instances like this. Always use create_user()
method to create users.
Source:stackexchange.com