The blank
option is used in the form validation, and the null
is used when writing to database.
So you might add null=True
to that field.
EDIT: continue the comment
Considering the two steps when saving object:
- Validator(controlled by
blank
)
- Database limitation(controlled by
null
)
For default
option, take IntegerField
for example,
default=5, blank=True, null=False
, pass (1) even if you didn't assign a value(having blank=True
), pass (2) because it has a default value(5) and writes 5
instead of None
to DB.
blank=True, null=False
, which pass (1) but not (2), because it attempts to write None
to DB.
Thus, if you want to make a field optional, use either default=SOMETHING, blank=True, null=False
or blank=True, null=True
.
Another exception is the string-like field, such as CharField
.
It's suggested that use the blank=True
alone, leaving null=False
behind.
This makes a field either a string(>=1 char(s)) or a empty string('', with len()==0), and never None
.
The reason is that when null=True
is set, there will be two possible value for the state "unset": empty string and None
, which is confusing(and might causing bugs).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…