What is the Difference Between null=True and blank=True in Django Model Fields?

Django model allows us to use empty values in model fields. Sometimes, it becomes necessary to keep the database columns empty for various purposes. We can update the fields later when it’s necessary. In such cases, we should use blank=True or null=True in models to avoid errors when populating the database tables.

What is blank=True?

blank determines whether the field is required in forms. If blank is set to True, the field isn’t required, whereas if it’s False the field cannot be blank.

By default, blank is set to False by Django. So, you can’ store the empty string(”) in the database field. You have to provide a valid value for the field in order to save the data.

What is null=True?

Here, you can store null as the value in the database, but you have to fill the form for the field and set it as null. If you don’t fill the form with a null value, it will raise an error. Usually, null=True is used for non-string fields. It is useful only when you want to store null as the value in the database.

Key Difference Between blank=True & null=True

if the field is set blank=True & null=True, it is optional in all circumstances. You don’t need to care about the field at all.

  • if blank=True and null=False, you needn’t provide any value for the field, but the database requires a non null value.
  • if null is set True and blank=False, the form requires a valid value but the database doesn’t.

When to Use blank=True?

You should use blank=True only when you wish to store empty values in a field. It can be used for all the model fields.

When to Use null=True?

This field is used for all non-string fields. If you set null for string-based fields, Django will get confused about what value to store as both empty string and null can be used to store the value.

Conclusion

You have to set blank=True for both string-based and non-string-based fields, if you wish to permit empty values in forms, as the null parameter only affects the database storage.