Django ModelForm 不允许必填字段为空值?

Django ModelForm won't allow Null value for required field?

我有一个包含该字段的模型...

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 select 下拉列表,顶部有一个空白值选项。每次我 select 空白选项并单击保存时,表单都不会在我的模型上将其保存为空值。它会保存任何其他字段,但不会保存空白字段。它会告诉我该字段也是必需的。

如何告诉表单只将空白值保存为 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