[Answered ]-Why django does not validate email in CustomUser model?

1👍

Django does not run validators automatically outside of ModelForm‘s.

So when you do this:

CustomUser.objects.create_user(email='dave') # creates user!

The EmailField‘s validators (i.e. EmailValidator) will not be run. An error will only be thrown if the database has an issue with the value you are trying to assign. In this case it won’t, because under the hood an EmailField is identical to a CharField and you’re passing it a string ('dave').

How validators are run (Django docs):

Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form.

I can understand the confusion. Your intuition is telling you that something defined in the models will be enforced by the ORM regardless of how it’s represented in the database. The reality is that a lot of the Model field options are only used in forms (blank, choices, editable, help_text etc.).

👤elyas

0👍

From the source, the class AbstractUser doesn’t define a validator for the emailfield, but one for username.

So if you want a validation from the model’s field, you have to do it yourself.
(and overwritte the username if you want to change it)

Leave a comment