Django - 无法从TypedChoiceField中删除empty_label

tun*_*rob 4 django django-forms

我的模型中有字段:

TYPES_CHOICES = (
    (0, _(u'Worker')),
    (1, _(u'Owner')),
)
worker_type = models.PositiveSmallIntegerField(max_length=2, choices=TYPES_CHOICES)
Run Code Online (Sandbox Code Playgroud)

当我在ModelForm中使用它时,它具有"---------"空值.它是TypedChoiceField所以它没有empty_label属性.所以我不能在表单init方法中覆盖它.

有没有办法删除"---------"?

该方法也不起作用:

def __init__(self, *args, **kwargs):
        super(JobOpinionForm, self).__init__(*args, **kwargs)
        if self.fields['worker_type'].choices[0][0] == '':
            del self.fields['worker_type'].choices[0]
Run Code Online (Sandbox Code Playgroud)

编辑:

我设法让它以这种方式工作:

def __init__(self, *args, **kwargs):
    super(JobOpinionForm, self).__init__(*args, **kwargs)
    if self.fields['worker_type'].choices[0][0] == '':
        worker_choices = self.fields['worker_type'].choices
        del worker_choices[0]
        self.fields['worker_type'].choices = worker_choices
Run Code Online (Sandbox Code Playgroud)

Ben*_*vis 5

任何模型字段的空选项,其中的选项在.formfield()模型字段类的方法中确定.如果您查看此方法的django源代码,该行如下所示:

include_blank = self.blank or not (self.has_default() or 'initial' in kwargs)
Run Code Online (Sandbox Code Playgroud)

因此,避免空选项的最简洁方法是在模型的字段上设置默认值:

worker_type = models.PositiveSmallIntegerField(max_length=2, choices=TYPES_CHOICES, 
                                               default=TYPES_CHOICES[0][0])
Run Code Online (Sandbox Code Playgroud)

否则,您将.choices在表单的__init__方法中手动黑客攻击表单字段的属性.