Django null Is a Database Setting, blank Is a Validation Setting

In progress Django

On a Django model field, null decides whether the database column accepts NULL, and blank decides whether forms, including the admin, accept an empty value. The two are independent, so an optional field needs a deliberate pair, and the right pair depends on the field type.

What Each Option Controls

Option Layer True means
null database column the column is nullable and can store NULL
blank form and model validation (full_clean()) an empty value passes validation

Both default to False: a field is required in forms and NOT NULL in the database.

Pick the Pair by Field Type

  • Non-string fields (IntegerField, DateField, ForeignKey…): an optional value needs both, so the form accepts an empty input and the database stores it as NULL. Example: age = models.PositiveIntegerField(null=True, blank=True).
  • String fields (CharField, TextField, SlugField, EmailField…): use blank=True alone. The empty string "" is then the only value for "no data".

The Exception for Unique Strings

A CharField with unique=True and blank=True also needs null=True. Several rows saved empty would all hold "" and break the unique constraint, whereas several NULL values don't count as duplicates.

References

Review cards

Flashcard Why does a CharField with unique=True and blank=True also need null=True?

Rows saved empty would all hold the empty string "" and break the unique constraint, whereas several NULL values don't count as duplicates.

Flashcard What is the default value for `null` and `blank` on a Django model field?

Both default to False, meaning the field is required in forms and NOT NULL in the database.

Quiz A form submits an empty value for IntegerField(blank=True) without null=True. What happens?
  • The field is saved as 0
  • Saving fails with an IntegrityError on the NOT NULL column
  • The form rejects the empty value
  • Django stores an empty string

blank lets the empty value through validation and it becomes None, which the NOT NULL column refuses.