我的模型中有字段:
TYPES_CHOICES = (
(0, _(u'Worker')),
(1, _(u'Owner')),
)
worker_type = models.PositiveSmallIntegerField(max_length=2, choices=TYPES_CHOICES)
当我在 ModelForm 中使用它时,它具有“---------”空值。它是 TypedChoiceField 所以它没有 empty_label 属性。所以我不能在表单 中覆盖它。初始化 方法。
有什么办法可以去掉那个“---------”?
该方法也不起作用:
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]
编辑:
我设法让它以这种方式工作:
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
最佳答案
任何模型字段的空选项,其选择在 .formfield()
中确定模型字段类的方法。如果您查看此方法的 django 源代码,该行如下所示:
include_blank = self.blank or not (self.has_default() or 'initial' in kwargs)
因此,避免空选项的最简洁方法是在模型的字段上设置默认值:
worker_type = models.PositiveSmallIntegerField(max_length=2, choices=TYPES_CHOICES,
default=TYPES_CHOICES[0][0])
否则,您只能手动破解
.choices
表单的 __init__
中表单字段的属性方法。
关于Django - 无法从 TypedChoiceField 中删除 empty_label,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8928565/