ModelForm required = True表现不尽如人意

时间:2018-04-26 13:33:43

标签: django django-forms

我正在使用Django 1.11

我没有得到ModelForm docs所期望的行为......

  

此外,每个生成的表单字段都具有如下设置的属性:

     

如果模型字段为空= True,则将required设置为False   表格字段。否则,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的其他部分没有影响,比如在管理员中创建用户。

2 个答案:

答案 0 :(得分:0)

我从来没有使用BooleanField。但它适用于IntegerField就好了。类似的东西:

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

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

答案 1 :(得分:0)

根据docs forms.BooleanField默认情况下(空时)返回False
另外models.BooleanField只能TrueFalse - 因此默认需要一些值。

UPDATE 我在BooleanField(Django 1.11)的源代码中找到了:

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

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

更新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})

P.S。正如你在评论中看到的那样 - 这正是我所说的,几乎是逐字逐句:D

相关问题