Coder Perfect

In Django, what is the difference between null=True and blank=True?

Problem

In Django, when we add a database field, we usually write:

models.CharField(max_length=100, null=True, blank=True)

ForeignKey, DecimalField, and other fields are treated similarly. What is the fundamental difference between having and not having

in terms of several fields (CharField, ForeignKey, ManyToManyField, DateTimeField) What are the benefits and drawbacks of employing 1/2/3?

Asked by user993563

Solution #1

null=True makes the column in your database NULL (rather than NOT NULL). In the database, blank values for Django field types like DateTimeField or ForeignKey will be stored as NULL.

If a field is left blank, it will not be required in forms. This includes the admin and any custom forms you’ve created. If blank=True, the field is not necessary; nevertheless, if blank=False, the field cannot be blank.

Because allowing a field to be blank in your form usually necessitates allowing NULL values for that column in your database, the two are frequently used together. The only exceptions are CharFields and TextFields, which are never saved as NULL in Django. In the database, blank values are recorded 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 choices aren’t rational to use (though null=True, blank=False might be useful if you want a field to always be needed in forms but optional when dealing with an object through 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

Django never saves CHAR and TEXT types as NULL, therefore null=True is redundant. You can, however, assign one of these fields to None to compel it to become NULL. If you have a scenario where that might be necessary, you should still include null=True.

Answered by Chris Pratt

Solution #2

For Django 1.8, this is how the ORM maps blank and null fields.

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 following database fields were added to PostgreSQL 9.4:

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)
)

For MySQL 5.6, the following database fields were added:

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
)

Answered by user

Solution #3

The choices in a Django model field declaration serve (at least) two purposes: establishing database tables and defining the default format and validation of model forms. (I say “default” because the settings can be altered at any time by supplying a custom form.) Some options have an impact on the database, while others have an impact on both.

Other responses have already stated that the former affects database table definition and the latter affects model validation when it comes to null and blank. Looking at use cases for all four conceivable configurations, I believe the distinction may be made even clearer:

Answered by Kevin Christopher Henry

Solution #4

Link, as stated in the Django Model Field reference:

Answered by Diogo

Solution #5

You may have your solution, but deciding whether to use null=True, blank=True, or both in a field remains a challenge. Providing so many options to developers, in my opinion, is both unnecessary and perplexing. Allow them to handle nulls or blanks as they see fit.

I follow this table, from Two Scoops of Django:

Answered by saran3h

Post is based on https://stackoverflow.com/questions/8609192/what-is-the-difference-between-null-true-and-blank-true-in-django