null vs blank Field in Django Model

In Django models, the terms blank and null are used to define the behavior of fields at both the application (validation) and database levels. Here’s a detailed comparison:

blank

  • Definition: blank=True specifies whether the field is allowed to be empty in forms.
  • Behavior: This is strictly a validation feature. If blank=True, Django will allow the field to be empty in forms and during model validation. If blank=False, the field is required.
  • Usage: Commonly used for form validation in Django Admin, serializers, and form classes.
  • Example:
    class MyModel(models.Model):
        name = models.CharField(max_length=100, blank=True)
    

null

  • Definition: null=True specifies whether the database column will accept NULL values.
  • Behavior: This is a database feature. If null=True, Django will store NULL in the database when a field has no value. If null=False, the field cannot have NULL in the database and must have some default or empty value.
  • Usage: Used when you want to explicitly allow NULL values at the database level, typically for non-string fields.
  • Example:
    class MyModel(models.Model):
        age = models.IntegerField(null=True)
    

Combined Usage

  • String-based fields: For character-based fields such as CharField and TextField, it’s recommended to use blank=True and null=False. This means empty values will be stored as empty strings ('') rather than NULL.
    class MyModel(models.Model):
        description = models.TextField(blank=True, null=False)
    
  • Non-string-based fields: For non-string fields, you may often see both blank=True and null=True to allow both empty values in forms and NULL values in the database.
    class MyModel(models.Model):
        birth_date = models.DateField(blank=True, null=True)
    

Summary

  • blank=True: Allows the field to be empty in forms.
  • null=True: Allows the field to store NULL in the database.
  • Common Pattern:
    • For strings: blank=True, null=False
    • For non-strings: blank=True, null=True

These settings provide flexibility in how you handle empty and null values in your Django models and forms.

References
https://docs.djangoproject.com/en/5.0/ref/models/fields/