Django models API offers two similar options that usually cause confusion on many developers:
I first started working with Django I couldn’t tell the difference and always ended up using both. Sometimes even using
Both do almost the same thing, as the name suggests, but here is the difference:
- Null: It is database-related. Defines if a given database column will accept null values or not.
- Blank: It is validation-related. It will be used during forms validation, when calling
That being said, it is perfectly fine to have a field with
blank=False. Meaning on the database level
the field can be NULL, but in the application level it is a required field.
Now, where most developers get it wrong: Defining
null=True for string-based fields such as
TextField. Avoid doing that. Otherwise, you will end up having two possible values for “no data”, that is: None
and an empty string. Having two possible values for “no data” is redundant. The Django convention is to use the
empty string, not NULL.
So, if you want a string-based model field to be “nullable”, prefer doing that:
The default values of
blank are False.
Also there is a special case, when you need to accept NULL values for a