What is the difference between null=True and blank=True in Django?
Solution 1:
null=True
sets NULL
(versus NOT NULL
) on the column in your DB. Blank values for Django field types such as DateTimeField
or ForeignKey
will be stored as NULL
in the DB.
blank
determines whether the field will be required in forms. This includes the admin and your custom forms. If blank=True
then the field will not be required, whereas if it's False
the field cannot be blank.
The combo of the two is so frequent because typically if you're going to allow a field to be blank in your form, you're going to also need your database to allow NULL
values for that field. The exception is CharField
s and TextField
s, which in Django are never saved as NULL
. Blank values are stored in the DB as an empty string (''
).
A few examples:
models.DateTimeField(blank=True) # raises IntegrityError if blank
models.DateTimeField(null=True) # NULL allowed, but must be filled out in a form
Obviously, Those two options don't make logical sense to use (though there might be a use case for null=True, blank=False
if you want a field to always be required in forms, optional when dealing with an object through something like the shell.)
models.CharField(blank=True) # No problem, blank is stored as ''
models.CharField(null=True) # NULL allowed, but will never be set as NULL
CHAR
and TEXT
types are never saved as NULL
by Django, so null=True
is unnecessary. However, you can manually set one of these fields to None
to force set it as NULL
. If you have a scenario where that might be necessary, you should still include null=True
.
Solution 2:
This is how the ORM maps blank
& null
fields for Django 1.8
class Test(models.Model):
charNull = models.CharField(max_length=10, null=True)
charBlank = models.CharField(max_length=10, blank=True)
charNullBlank = models.CharField(max_length=10, null=True, blank=True)
intNull = models.IntegerField(null=True)
intBlank = models.IntegerField(blank=True)
intNullBlank = models.IntegerField(null=True, blank=True)
dateNull = models.DateTimeField(null=True)
dateBlank = models.DateTimeField(blank=True)
dateNullBlank = models.DateTimeField(null=True, blank=True)
The database fields created for PostgreSQL 9.4 are :
CREATE TABLE Test (
id serial NOT NULL,
"charNull" character varying(10),
"charBlank" character varying(10) NOT NULL,
"charNullBlank" character varying(10),
"intNull" integer,
"intBlank" integer NOT NULL,
"intNullBlank" integer,
"dateNull" timestamp with time zone,
"dateBlank" timestamp with time zone NOT NULL,
"dateNullBlank" timestamp with time zone,
CONSTRAINT Test_pkey PRIMARY KEY (id)
)
The database fields created for MySQL 5.6 are :
CREATE TABLE Test (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`charNull` VARCHAR(10) NULL DEFAULT NULL,
`charBlank` VARCHAR(10) NOT NULL,
`charNullBlank` VARCHAR(10) NULL DEFAULT NULL,
`intNull` INT(11) NULL DEFAULT NULL,
`intBlank` INT(11) NOT NULL,
`intNullBlank` INT(11) NULL DEFAULT NULL,
`dateNull` DATETIME NULL DEFAULT NULL,
`dateBlank` DATETIME NOT NULL,
`dateNullBlank` DATETIME NULL DEFAULT NULL
)
Solution 3:
It's crucial to understand that the options in a Django model field definition serve (at least) two purposes: defining the database tables, and defining the default format and validation of model forms. (I say "default" because the values can always be overridden by providing a custom form.) Some options affect the database, some options affect forms, and some affect both.
When it comes to null
and blank
, other answers have already made clear that the former affects the database table definition and the latter affects model validation. I think the distinction can be made even clearer by looking at use cases for all four possible configurations:
null=False
,blank=False
: This is the default configuration and means that the value is required in all circumstances.null=True
,blank=True
: This means that the field is optional in all circumstances. (As noted below, though, this is not the recommended way to make string-based fields optional.)-
null=False
,blank=True
: This means that the form doesn't require a value but the database does. There are a number of use cases for this:The most common use is for optional string-based fields. As noted in the documentation, the Django idiom is to use the empty string to indicate a missing value. If
NULL
was also allowed you would end up with two different ways to indicate a missing value.Another common situation is that you want to calculate one field automatically based on the value of another (in your
save()
method, say). You don't want the user to provide the value in a form (henceblank=True
), but you do want the database to enforce that a value is always provided (null=False
).Another use is when you want to indicate that a
ManyToManyField
is optional. Because this field is implemented as a separate table rather than a database column,null
is meaningless. The value ofblank
will still affect forms, though, controlling whether or not validation will succeed when there are no relations.
-
null=True
,blank=False
: This means that the form requires a value but the database doesn't. This may be the most infrequently used configuration, but there are some use cases for it:It's perfectly reasonable to require your users to always include a value even if it's not actually required by your business logic. After all, forms are only one way of adding and editing data. You may have code that is generating data which doesn't need the same stringent validation that you want to require of a human editor.
Another use case that I've seen is when you have a
ForeignKey
for which you don't wish to allow cascade deletion. That is, in normal use the relation should always be there (blank=False
), but if the thing it points to happens to be deleted, you don't want this object to be deleted too. In that case you can usenull=True
andon_delete=models.SET_NULL
to implement a simple kind of soft deletion.
Solution 4:
As said in Django Model Field reference: Link
Field options
The following arguments are available to all field types. All are optional.
null
Field.null
IfTrue
, Django will store empty values asNULL
in the database. Default isFalse
.Avoid using
null
on string-based fields such asCharField
andTextField
because empty string values will always be stored as empty strings, not asNULL
. If a string-based field hasnull=True
, that means it has two possible values for "no data":NULL
, and the empty string. In most cases, it’s redundant to have two possible values for "no data"; the Django convention is to use the empty string, notNULL
.For both string-based and non-string-based fields, you will also need to set
blank=True
if you wish to permit empty values in forms, as thenull
parameter only affects database storage (seeblank
).Note
When using the Oracle database backend, the value NULL will be stored to denote the empty string regardless of this attribute
blank
Field.blank
If
True
, the field is allowed to be blank. Default isFalse
.Note that this is different than
null
.null
is purely database-related, whereasblank
is validation-related. If a field hasblank=True
, form validation will allow entry of an empty value. If a field hasblank=False
, the field will be required.
Solution 5:
You may have your answer however till this day it's difficult to judge whether to put null=True or blank=True or both to a field. I personally think it's pretty useless and confusing to provide so many options to developers. Let the handle the nulls or blanks however they want.
I follow this table, from Two Scoops of Django: