Django - What does blank=True and null=True mean?

/ #Django

I often use blank=True and null=True in database models in my Django videos. What's the difference between them?

Blank and null is sort of the same thing. Using both of them is what I almost always end up using. But it can actually be wrong.

What is Blank?

Blank is used for validation. So when we use Django forms, the admin area and similar, Django will use this for checking if the field is required or not.

What is Null?

Null is used for database related things. It tells the database if the columns should accept null values or not.

An example

class Post(models.Model):
    title = models.CharField(max_length=255)
    intro = models.TextField(blank=True)
    published = models.DateTimeField(blank=True, null=True)

The title field will be required. The intro field is optional, but as you can see, I haven't set null=True. This makes Django store the intro field as an empty string if there is no value. So it will actually not be stored as NULL.

The published field on the other hand will be stored as NULL if there is no value.

So the way this is done now is the correct way. Fields such as TextField, CharField, EmailField and similar (String based fields) should not be stored as NULL. This is because then you will have two ways "empty" can be stored in the database. Both empty strings and NULL.


No comments yet...

Add comment


Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.