Table of Content
- Difference Between Blank and Null in Django
- Using Both Blank and Null Property in Django
- Common Mistakes When Using Both Blank and Null Property
- Wrap Off
In Django models, there are two field properties for leaving a field empty that usually causes confusion for many developers.
This is the
When you start working with Django for the first time, you may not be able to tell the difference, and might simply end up using both.
And other times, incorrectly using them.
The good thing is, if your aim was to leave a field empty, you're not wrong in thinking both do almost the same thing, as the name suggests.
But there is the catch. And that is what differentiates them.
Difference Between Blank and Null in Django
Here's the difference between blank and null in Django:
Null: Null is related to the database and defines if a given database column can be empty or not.
Blank: Blank is related to validation and will be used during forms validation in Django, especially when calling
Using Both Blank and Null Property in Django
It is perfectly fine to have a model field with
What this means is that, the field can be NULL and accept empty values on the database level, but in the application level during form validation, it is a required field.
Common Mistakes When Using Both Blank and Null Property
Here are common mistakes most developers make when using Null and Blank property:
null=Truefor string-based fields such as
This is wrong because it makes it possible to have two values that represent “empty data”, that is: None and an empty string.
This creates data redundancy.
The Django convention is to use the empty string, not NULL.
This means that if you want a string-based model field to be “nullable”, here's how you can do it:
class Book(models.Model): title = models.CharField(max_length=255) # Mandatory summary = models.TextField(max_length=500, blank=True) # Optional (don't put null=True) release_date = models.DateField(null=True, blank=True) # Optional (here you may add null=True)
Highlighted code sample.
From the code snippet above, in the
release_datefield, the default values of
NullBooleanFieldinstead for setting null to false, when you need to accept NULL values for a
There you have it! I hope you found this post useful somehow.
If you have any questions or need clarification, feel free to reach out to me.
If you learned from this tutorial, or it helped you in any way, please consider sharing and subscribing to our newsletter.