Django-无法从TypedChoiceField中删除empty_label [英] Django - Can't remove empty_label from TypedChoiceField

查看:52
本文介绍了Django-无法从TypedChoiceField中删除empty_label的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型中有字段:

TYPES_CHOICES = (
    (0, _(u'Worker')),
    (1, _(u'Owner')),
)
worker_type = models.PositiveSmallIntegerField(max_length=2, choices=TYPES_CHOICES)

当我在ModelForm中使用它时,它具有"---------"空值.它是TypedChoiceField,所以没有empty_label属性.因此,我无法以 init 方法的形式覆盖它.

When I use it in ModelForm it has "---------" empty value. It's TypedChoiceField so it hasn't empty_label attribute., so I can't override it in form init method.

有什么方法可以删除"---------"吗?

Is there any way to remove that "---------"?

该方法也不起作用:

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]

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

I managed to make it work in that way:

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源代码,则该行如下所示:

The empty option for any model field with choices determined within the .formfield() method of the model field class. If you look at the django source code for this method, the line looks like this:

include_blank = self.blank or not (self.has_default() or 'initial' in kwargs)

因此,避免为空的最干净方法是在模型字段上设置默认值:

So, the cleanest way to avoid the empty option is to set a default on your model's field:

worker_type = models.PositiveSmallIntegerField(max_length=2, choices=TYPES_CHOICES, 
                                               default=TYPES_CHOICES[0][0])

否则,您将不得不手动破解表单的 __ init __ 方法中表单字段的 .choices 属性.

Otherwise, you're left with manually hacking the .choices attribute of the form field in the form's __init__ method.

这篇关于Django-无法从TypedChoiceField中删除empty_label的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆