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

标签 python django django-models django-forms

我有一个带有这个字段的模型...

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/

相关文章:

Python:如何将每小时值拆分为 15 分钟的桶?

python - Cython 内存 View : wrapping c function with array parameter to pass numpy array

python - 对于具有标准用户模型的具有外键的模型,RelatedObjectDoesNotExist

django - 访问 Django 中介模型值

python - 正确打印列表条目剂量格式

javascript - 类型错误状态文本 : "Internal Server Error" for a simple post "LIKE" feature in Django using Ajax

python - Django从另一个表过滤对象外键

python - Django导入错误: No module named allauth.

Django ORM 和 SQL 内连接

django - 特定 Django 模型的高级搜索