Django-Can';t从TypedChoiceField中删除空的_标签

Django-Can';t从TypedChoiceField中删除空的_标签,django,django-forms,Django,Django Forms,我的模型中有一个字段: TYPES_CHOICES = ( (0, _(u'Worker')), (1, _(u'Owner')), ) worker_type = models.PositiveSmallIntegerField(max_length=2, choices=TYPES_CHOICES) 当我在ModelForm中使用它时,它有一个“-----------”空值。它是TypedChoiceField,所以它没有空的标签属性,所以我不能在表单init方法中重写它

我的模型中有一个字段:

TYPES_CHOICES = (
    (0, _(u'Worker')),
    (1, _(u'Owner')),
)
worker_type = models.PositiveSmallIntegerField(max_length=2, choices=TYPES_CHOICES)
当我在ModelForm中使用它时,它有一个“-----------”空值。它是TypedChoiceField,所以它没有空的标签属性,所以我不能在表单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]
编辑:

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

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])

否则,您就只能手动破解表单的
\uuuu init\uuuuuu
方法中表单字段的
.choices
属性。

self.fields['xxx']。如果字段类型为
TypedChoiceField
且没有
空标签
属性,则空值=无
将不起作用。 我们应该做的是删除第一选择:

class JobOpinionForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(JobOpinionForm, self).__init__(*args, **kwargs)

        for field_name in self.fields:
            field = self.fields.get(field_name)
            if field and isinstance(field , forms.TypedChoiceField):
                field.choices = field.choices[1:]

它不起作用。我编辑了我的帖子并粘贴了工作方案。不知道这是不是最好的,我不知道。当我打印它时,我得到的是空数据,但在站点上它显示“----”。将其设置为其他类似的内容:self.fields['worker\u type'].empty\u value='nothing'也不起作用:)
TypedChoiceField
没有
empty\u标签
class JobOpinionForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(JobOpinionForm, self).__init__(*args, **kwargs)

        for field_name in self.fields:
            field = self.fields.get(field_name)
            if field and isinstance(field , forms.TypedChoiceField):
                field.choices = field.choices[1:]