What is the difference between null=True and blank=True in Django Field?
Published on Aug. 22, 2023, 12:12 p.m.
When we add a model field in Django.
models.CharField(max_length=100, null=True, blank=True)
What is the basic differences between:
Null=True sets NULL (versus NOT NULL) in your DB.ForeignKey will be stored as NULL in the DB.
The field will be required in forms, if the blank is required.If blank=True then the field will not be required.
The combo of the two is so frequent because typically you’re going to allow a field to be blank in your form.The exception is CharFields and TextFields. They are never saved as NULL in Django.In theDB, the marker values are stored as an empty string (‘’).
models.DateTimeField(blank=True) # raises IntegrityError if blank
models.DateTimeField(null=True) # NULL allowed, but must be filled out in a form
models.CharField(blank=True) # No problem, blank is stored as ''
models.CharField(null=True) # NULL allowed, but will never be set as NULL
CHAR and TEXT types are NEVER saved as NULL by Django.However, you can manually set one of these fields to None.If you have a scenario where that might be necessary, you should .