简体   繁体   English

Django ModelForm不允许在必填字段中使用Null值吗?

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

I have a Model with this field... 我有这个领域的模特...

fulfillment_flag = models.CharField(pgettext_lazy('Delivery group field', 'Fulfillment Flag'), max_length=255,
                                        null=True, choices=FULFILLMENT_FLAG_CHOICES)

And here is my form... 这是我的表格

class FulfillmentFlagForm(forms.ModelForm):

    class Meta:
        model = DeliveryGroup
        fields = ['fulfillment_flag', ]

    def clean_fulfillment_flag(self):
        return self.cleaned_data['fulfillment_flag'] or None

I have an HTML select drop down that has a blank value option at the top. 我有一个HTML select下拉列表,顶部有一个空白值选项。 Every time I select the blank option and click Save, form will not save it as a Null value on my model. 每次我选择空白选项并单击“保存”时,表单都不会将其另存为模型中的Null值。 It'll save any of the other fields though, just not the blank one. 但是,它将保存其他任何字段,而不是空白字段。 And it will tell me that the field is required as well. 它会告诉我该字段也是必需的。

How can I tell the form to just save the blank value as Null? 如何告诉表单将​​空白值另存为Null?

https://docs.djangoproject.com/en/1.8/ref/models/fields/#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. 避免在基于字符串的字段(如CharField和TextField)上使用null,因为空字符串值将始终存储为空字符串,而不是NULL。 If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. 如果基于字符串的字段具有null = True,则意味着它具有“无数据”的两个可能值:NULL和空字符串。 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. 在大多数情况下,为“无数据”使用两个可能的值是多余的; Django约定是使用空字符串,而不是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,因为null参数仅影响数据库存储(请参见空白)。

Do blank=True instead and save "" instead of None . 改用blank=True并保存""而不是None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM