null and blank attributes in Django- Explained



Python


In this article, we go over null and blank attributes in Django and the difference between the two.

So both null and blank and are boolean attributes that accept either True or False as values.


null attribute

null is an attribute that is strictly for databases. So if you are creating a database field, you can set the value of null to either True or False. If you set the null value to True, then this means that nothing can be in the database table. If you set null equal to false, then the database field that is set equal to null must contain a value.

By default, in Django, null is equal to True.

Django thinks of it like this. The database at all times have to have values in them. When you originally a create a database in the models.py file, Django creates the columns that you specify along with whether a value is in them or not. Because you don't create a database and populate it at the same time, the rows of the columns have no value in them initially. But there always has to be a value in each column of a database table in Django unless null is equal to True.

You pretty much never want to set null equal to False, unless you're specifying a default value for the field. If you try to makemigrations on a database table in which a field has null equal to False, with no default value specified, Django will ask you for a one-off default. It needs the database populated, unless, of course, null is set equal to False.

So that's null in a nutshell.


blank attribute

blank is an attribute for determining whether a field is required or not.

Just like null, blank can be set either to True or False.

If blank is set equal to True, this means that the field isn't required. A user can enter nothing into that field and it will pass validation.

If blank is set equal to False, this means that the field is required. A user must enter some valid data into the field, or else the form will not pass validation and be submitted.

By default, in Django, blank is set equal to False, meaning that the field is required.

So, in summary, null is an attribute for databases. Databases must always have a value in Django, unless you specifically set null equal to True. If null equals to False, you must provide a default value for the field, so that the database table can be populated. By default, in Django, null is equal to True. blank is an attribute for form validation and submission, whether the field can be entered in blank or not. If blank is set equal to True, the field isn't required. If blank is set equal to False, the field is required. By default, in Django, blank is set equal to False, meaning the field is required.

And this is all there is to null and blank attributes in Django.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...