What is the difference between null=True and blank=True in Django?
In Django, null=True
and blank=True
are both used to specify options for fields in a model.
null=True
specifies that the field can be set to NULL
in the database. This means that the field can be left empty or unassigned in the model, and the database will store it as NULL
instead of a default value. For example:
class MyModel(models.Model):
my_field = models.CharField(max_length=255, null=True)
blank=True
specifies that the field can be left blank when creating or updating a model instance. This means that the field can be left empty or unassigned in a form, and the model will still be valid. For example:
class MyModel(models.Model):
my_field = models.CharField(max_length=255, blank=True)
Watch a video course
Python - The Practical Guide
It's worth noting that blank=True
implies null=True
. So, if you set blank=True
, you don't need to set null=True
as well.
class MyModel(models.Model):
my_field = models.CharField(max_length=255, blank=True, null=True)
In this example, my_field
can be left blank or unassigned both in the form and in the database.