I have some model fields for which values should be optional. As per the docs, I set blank but not null. Manage.py makemigrations
says I need a default value even though it's empty, no problem:
我有一些模型字段,其值应该是可选的。根据文档,我设置为空白但不为空。 Manage.py makemigrations说我需要一个默认值,即使它是空的,没问题:
address = models.CharField(max_length=100, blank=True, default="")
And yet when I use this in a form, form validation comes back with "this field is required".
然而,当我在表单中使用它时,表单验证将返回“此字段是必需的”。
The form looks like this:
表单如下所示:
address = forms.CharField(max_length=128)
And the solution was simply that the form needed to look like this instead:
而解决方案只是表单需要看起来像这样:
address = forms.CharField(max_length=128, required=False)
See the doc link at the beginning of the second sentence for why using null=True
is not the right thing to do.
请参阅第二句开头的doc链接,了解为什么使用null = True不是正确的做法。
2 个解决方案
#1
1
I think you need to clearly understand the difference between : null = True and blank = True.
我想你需要清楚地理解:null = True和blank = True之间的区别。
null = true, is used when the value of a particular field is optional. blank = true, is used when the value of the field is to be rendered as 'required' field while using it in forms.
当特定字段的值是可选的时,使用null = true。 blank = true,当在表单中使用字段的值时将其呈现为“required”字段时使用。
They are together used for certain fields to ensure that, the particular field's value is optional. So here, instead of using blank=True, enforce null=True to make the value for first_name optional.
它们一起用于某些字段,以确保特定字段的值是可选的。所以这里,而不是使用blank = True,强制执行null = True以使first_name的值可选。
#2
0
Aha, the form field should be flagged with required=False
. I've updated the question to show the corrected line in full.
Aha,表单字段应标记为required = False。我已更新问题以完整显示更正后的行。
参考
#1
1
I think you need to clearly understand the difference between : null = True and blank = True.
我想你需要清楚地理解:null = True和blank = True之间的区别。
null = true, is used when the value of a particular field is optional. blank = true, is used when the value of the field is to be rendered as 'required' field while using it in forms.
当特定字段的值是可选的时,使用null = true。 blank = true,当在表单中使用字段的值时将其呈现为“required”字段时使用。
They are together used for certain fields to ensure that, the particular field's value is optional. So here, instead of using blank=True, enforce null=True to make the value for first_name optional.
它们一起用于某些字段,以确保特定字段的值是可选的。所以这里,而不是使用blank = True,强制执行null = True以使first_name的值可选。
#2
0
Aha, the form field should be flagged with required=False
. I've updated the question to show the corrected line in full.
Aha,表单字段应标记为required = False。我已更新问题以完整显示更正后的行。
参考