【问题标题】:ModelForm required=True not behaving as expectedModelForm required=True 未按预期运行
【发布时间】:2018-04-26 13:33:42
【问题描述】:

我正在使用 Django 1.11

我没有从 ModelForm docs 那里得到我期望的行为...

另外,每个生成的表单域的属性设置如下:

如果model字段有blank=True,那么required设置为False on 表单域。否则,required=True。

我正在使用 ModelForm:

class TestForm(ModelForm):
    class Meta:
        model = CUser
        fields = '__all__'

以及底层模型:

class CUser(AbstractBaseUser):
    ...
    a_t = models.BooleanField()

但是我的表单域 a_t 没有设置 required=True 设置。 (我知道我可以在表单中创建字段来完成这项工作,但我很好奇为什么这不能按照(我理解的)它应该的方式工作)

我错过了什么?

编辑:

我的模型中也有这个:

REQUIRED_FIELDS = ['first_name','last_name']

但是the docs 也说这不应该影响事情......

REQUIRED_FIELDS 对 Django 的其他部分没有影响,例如在管理员中创建用户。

【问题讨论】:

  • 我猜这是一个复制错误,但你的模型没有继承自 models.Model :)
  • 是的,为了简洁起见,我正在重写。编辑修复。
  • @user2726394 提供更多说明。
  • @nawarkhede 嗯,我应该澄清什么?正如预期的那样,生成的表单不需要选中复选框。在字段上检查 .required 会返回 False

标签: django django-forms


【解决方案1】:

根据docsforms.BooleanField默认(为空时)返回False
另外,models.BooleanField 只能是 TrueFalse - 所以 默认 需要一些值。

更新我发现在 BooleanField (Django 1.11) 的源代码中:

def __init__(self, *args, **kwargs):
    kwargs['blank'] = True
    super(BooleanField, self).__init__(*args, **kwargs)

我认为这意味着默认 Django 为每个BooleanField 设置blank=True

更新 2 看起来它甚至在 Django 2.0 - 1020 行中有所改变:

def formfield(self, **kwargs):
        if self.choices:
            include_blank = not (self.has_default() or 'initial' in kwargs)
            defaults = {'choices': self.get_choices(include_blank=include_blank)}
        else:
            form_class = forms.NullBooleanField if self.null else forms.BooleanField
            # In HTML checkboxes, 'required' means "must be checked" which is
            # different from the choices case ("must select some value").
            # required=False allows unchecked checkboxes.
            defaults = {'form_class': form_class, 'required': False}
        return super().formfield(**{**defaults, **kwargs})

附:正如您在注释行中看到的那样 - 这正是我所说的,几乎是逐字逐句:D

【讨论】:

  • 好的,但是我给出的文档的第一行说,除非模型字段具有空白=True,否则表单字段属性“必需”将设置为 True。不是这种情况。表单字段属性“必需”设置为 false。
  • 什么意思?模型的 BooleanField 没有 blank=True。该字段没有此属性。
  • ModelForm 从模型生成表单,为 ModelForm 元“字段”列表中指定的每个模型字段创建一个表单字段。文档说每个生成的表单字段都需要=True(除非模型字段有空白=True)。我的表单字段没有像我期望的那样设置为 required=True。
  • 逻辑上required = True 的意思是:你必须在这个字段中输入一些值。如果 BooleanField 有 required = true - 这是否意味着它总是应该被选中?可能它没有require = True,因为它无论如何都会收到一些价值——例如defaultselected?这只是我对这个问题的想法。
  • 不,这不是必需的布尔字段的行为。我可以在表单中手动创建一个布尔字段并设置 required=True。这做了几件事: 1) 所需表单字段的小部件具有所需的 HTML 属性。 2)表单验证复选框被选中。 我只想知道为什么代码的行为不像文档中描述的那样
【解决方案2】:

我从来没有让这个与BooleanField 一起工作。但它适用于 IntegerField 就好了。比如:

YESNO_CHOICES = (
    (0, 'no'),
    (1, 'yes'),
)

a_t = models.IntegerField(default=1, choices=YESNO_CHOICES)

【讨论】:

    猜你喜欢
    • 2011-10-04
    • 2014-05-16
    • 2014-11-12
    • 1970-01-01
    • 2020-06-28
    • 2012-02-18
    • 2018-01-18
    • 2012-06-14
    • 2019-03-03
    相关资源
    最近更新 更多