【问题标题】:Django nullbooleanfield is defaulting to 'False' when left empty on form, shouldn't be Null?当表单上留空时,Django nullbooleanfield 默认为“False”,不应该为 Null 吗?
【发布时间】:2018-12-04 20:32:55
【问题描述】:

models.py

my_field = models.NullBooleanField(null=True)

forms.py

my_field = forms.BooleanField(
    label='my_field',
    required=False,
    widget=forms.RadioSelect(choices=[(True,'yes'),(False,'no')]))

提交表单时未选择单选按钮,表单将保存并默认为 false。它不应该默认为 Null 吗?

【问题讨论】:

  • 你不应该在表格中使用NullBooleanField吗?

标签: django


【解决方案1】:

您的表单使用forms.BooleanField 作为表单字段,因此它没有None 的概念。你应该使用NullBooleanField [Django-doc]:

class SomeForm(forms.Form):
    my_field = forms.NullBooleanField(
        label='my_field',
        required=False,
        widget=forms.RadioSelect(choices=[(True,'yes'),(False,'no')])
    )

正如documentation of the NullBooleanField 所说:

NullBooleanField

class NullBooleanField(**kwargs)

  • 默认小部件:NullBooleanSelect
  • 空值:None
  • 归一化为:Python True、False 或 None 值。
  • 不验证任何内容(即,它从不引发 ValidationError)。

而对于BooleanField,空值是False:

BooleanField

class BooleanField(**kwargs)

  • 默认小部件:CheckboxInput
  • 空值:False
  • 规范化为:Python True 或 False 值。
  • 如果字段有required=True,则验证值为True(例如选中复选框)。
  • 错误消息键:必需

【讨论】:

    猜你喜欢
    • 2012-08-13
    • 1970-01-01
    • 2012-02-27
    • 2015-02-21
    • 2018-11-18
    • 2019-09-26
    • 2011-06-04
    • 2016-09-05
    • 1970-01-01
    相关资源
    最近更新 更多