我有一个带有这个字段的模型...
fulfillment_flag = models.CharField(pgettext_lazy('Delivery group field', 'Fulfillment Flag'), max_length=255,
null=True, choices=FULFILLMENT_FLAG_CHOICES)
这是我的表格...
class FulfillmentFlagForm(forms.ModelForm):
class Meta:
model = DeliveryGroup
fields = ['fulfillment_flag', ]
def clean_fulfillment_flag(self):
return self.cleaned_data['fulfillment_flag'] or None
我有一个 HTML 选择下拉菜单,顶部有一个空白值选项。每次我选择空白选项并单击“保存”时,表单都不会在我的模型上将其保存为空值。它会保存任何其他字段,但不会保存空白字段。它会告诉我该字段也是必需的。
如何告诉表单只将空白值保存为 Null?
最佳答案
https://docs.djangoproject.com/en/1.8/ref/models/fields/#null
Avoid using null on string-based fields such as CharField and TextField because empty string values will always be stored as empty strings, not as NULL. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL.
For both string-based and non-string-based fields, you will also need to set blank=True if you wish to permit empty values in forms, as the null parameter only affects database storage (see blank).
改为执行 blank=True
并保存 ""
而不是 None
。
关于python - Django ModelForm 不允许必填字段为空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32057210/