What is the difference between blank and null in Django?
null=True would tell the underlying database that this field is allowed to save null. blank=True is applicable in the Django forms layer, i.e. any user is allowed to keep empty this field in Django form or Admin page. blank value is stored in the database.
The TLDR answer
null=True would tell the underlying database that this field is allowed to save null.
blank=True is applicable in the Django forms layer, i.e. any user is allowed to keep empty this field in Django form or Admin page. blank value is stored in the database.
The Detail answer
Whenever you are trying to define a Django model field this is the most common question which would come into your mind, should I use null=True or blank=True or both. Let me explain to you in detail what exactly this means
nullis database-related. It tells the underlying database whether the column would allownullvalue to be saved or not.blankis Django forms related. It is used for validation of Django forms, in admin or Django. Specifically when we callform.is_valid()
For example, let us see the below example-
class Company(models.Model):
name = models.CharField(max_length=100)
website = models.UrlField()
founded_on = models.DateField(blank=True)
random_date = models.DateFeild(null=True)
random_text = models.TextField(null=True, blank=True)I have defined a Company model which has 2 fields where we are playing around with blank and null options. Let's see what happens with the different fields
founded_onAnyone can send an empty string value when using admin or any form and it would be considered as a valid value. But when we would try to save the value to the database then we would raiseIntegrityError. But when we would send the data value then it would save the value to DB without any hiccup.random_dateWhen sending an empty value from the admin or form, it would through validation error, since it considers any date as valid data and empty string to be invalid data. But it also allows the column to benullat the database layer.random_textThis is the option that means that the field is allowed to be saved as null at the database layer and also empty string value is allowed to be valid data as per the Django admin or forms validation logic. You don't want to do this forTextFieldsince it would mean that the column can have two possible values when no data is supplied,empty string ('')andnull