Difference between Null and Blank in Django Model

Difference between Null and Blank in Django Model

Adam WaƘiƑ
·Mar 12, 2022·

2 min read

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.

sirkif-django-python.png

When we set:

  • null=True which means that we inform our database that we can store empty value as NULL, no-value, without any data, ( Default value of null is False ).

  • blank=True which 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 of blank is 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

  1. 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 ).

  2. Second, and this important is Null in SQL world is treated as Falsy value and Blank ( 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.

 
Share this