35

So far I haven't come across a clear explanation on blank, null, and required - in Django's models and forms.


I know the default for each is the following:

blank = False
null = False
required = True

I also know that:

blank=True (used in models.py), means on the form level, accept empty forms - the associated field is not required in a form.

null=True (used in models.py), means on the database level that Python None values can be stored in the model and be saved (and then end up as SQL NULL values in the database).

required=False (used in forms.py), means the associated form field is not required.


Hopefully the above information will serve others well (please let me know if there are any flaws in the logic, and I will update it).

My question is the following:

When do I know when to use blank=True vs. required=False. If my goal is to make a form field not required, I could define this in the model using blank=True, or I could define this in the form using required=False. Does this mean you can define blank=True in a model, and in the associated ModelForm override this with required=True?

Also related, what about when you are using a regular form (forms.Form)? Since the form is not associated with a model (other than through view logic), what happens if again, they contradict each other?

4

2 回答 2

19

The contradictions don't matter. I think this brings flexibility to the development of a Django application. For example, if you're using a third party library that defines some models, and they set blank=True, but for other purposes you need that field is mandatory, then in your forms you can fix it without touching the third party library code.

This just add some flexibility to the framework IMHO, that brings no harm. You can use it for your own purposes. The contradictions are not significant.

Hope this helps!

于 2013-06-19T18:58:30.873 回答
3

这取决于要求。有时我们决定稍后在表格上强制填写字段,尽管在模型上它仍然不是必需的。但表格将确保必须填写该字段。

您可以null=True在模型上使用,然后您可以在表单上将该字段设为必填项。但是,当模型上强制要求字段时,您不能在表单中将字段设为可选,这将导致稍后的数据库错误。

于 2013-06-19T18:56:46.553 回答