In Django, many of us have some confusion between these two fields in a model Null and Blank, in short:
- Null is related to a database.
- Blank is related to an HTML form.
When we set:
null=Truewhich means that we inform our database that we can store empty value as NULL, no-value, without any data, ( Default value ofnullis False ).blank=Truewhich means that our Form, our input will have a required attribute set to false ( by default is true ), then allow the user to enter an empty field, ( Default value ofblankis False which means the required attribute is True ).
Question
You may ask yourself when we have string-based fields in a model such as CharField and TextField, Null and Blank fields are set to True, then Django stores an empty string (" ") in a database instead of Null, WHY 🤔🤔?
Answers
First because when our user submits an empty value, our input will return an empty string ( HTML inputs
type="text"are always return string values ).Second, and this important is
Nullin SQL world is treated as Falsy value andBlank( empty string ) in Python world is also Falsy.
Therefore, it would be inefficient and redundant for Django to deal with two possible values that are treated as Falsy values ( No data & Empty String ).
Summary
Since the HTML input returns a string value at the end, Django preferred to use an empty string (" "), not Null.

Top comments (0)