Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are blank and null distinct options for a django model?

When defining fields in a django model, there are two ways to say that the field is allowed to be empty. null means it can be empty in the database, and blank says the field can be empty in a form. Why are these distinct? Every time I set one but not the other something goes wrong. Allowing them to be different seems to be to just inviting problems of the form allowing you to create objects the database won't accept.

In other words, when would you ever use null=True,blank=False or null=False,blank=True in a django model?

like image 370
Leopd Avatar asked Nov 16 '11 21:11

Leopd


2 Answers

They have two entirely different meanings:

blank: determines whether the field should be validated as required or not in forms. False means the form will generate an error if not provided, while True means empty values are allowed.

null: determines whether the field should be set as NULL or NOT NULL at the DB level. This has nothing to do with form validation.

Some examples:

blank=True, null=False would raise an IntegrityError anytime the field was left blank, if it's not a CharField or TextField. Those two fields send '' (empty string) rather than NULL to the DB when empty.

blank=False, null=True would always require the field to be filled out in all forms (forms will raise ValidationError on the field), even though the column is allowed to be NULL. However, this only applies to forms. You could manually set the attribute to None and save it outside of a form (in a shell, for example).

like image 89
Chris Pratt Avatar answered Oct 18 '22 17:10

Chris Pratt


null=False, blank=True is common for CharFields, where a blank answer is stored in the db as a blank string rather than a null. The other way around doesn't make much sense to use.

For non-string fields, a non-answer is stored as a null, and so you need both.

like image 44
second Avatar answered Oct 18 '22 15:10

second