Django - 无法从TypedChoiceField中删除empty_label [英] Django - Can't remove empty_label from TypedChoiceField
问题描述
TYPES_CHOICES =(
(0,_(u'Worker' )),
(1,_(u'Owner')),
)
worker_type = models.PositiveSmallIntegerField(max_length = 2,choices = TYPES_CHOICES)
当我在ModelForm中使用它时,它具有---------空值。它是TypedChoiceField,所以它没有empty_label属性,所以我不能以 init 方式覆盖它。
有没有办法删除那个---------?
该方法不起作用:
def __init __(self,* args,** kwargs):
/ pre>
super(JobOpinionForm,self).__ init __(* args,** kwargs)
如果自己.fields ['worker_type']。choices [0] [0] =='':
del self.fields ['worker_type']。choices [0]
编辑:
我设法使其以这种方式工作:
def __init __(self,* args,** kwargs):
super(JobOpinionForm,self).__ init __(* args,** kwargs )
如果self.fields ['worker_type']。choices [0] [0] =='':
worker_choices = self.fields ['worker_type']。choice
del worker_choices [ 0]
self.fields ['worker_type']。choices = worker_choices
解决方案模型字段类的
.formfield()
方法中确定的任何模型字段的空选项。如果您查看此方法的django源代码,则该行如下所示:include_blank = self.blank或not self.has_default()或kwargs中的initial)
所以,最简单的方法来避免空选项是在模型的字段上设置默认值:
worker_type = models.PositiveSmallIntegerField(max_length = 2,choices = TYPES_CHOICES,
default = TYPES_CHOICES [0] [0])
否则,在窗体的
__ init __
方法中隐藏表单字段的.choices
属性。I have field in my model:
TYPES_CHOICES = ( (0, _(u'Worker')), (1, _(u'Owner')), ) worker_type = models.PositiveSmallIntegerField(max_length=2, choices=TYPES_CHOICES)
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 "---------"?
That method doesn't work too:
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]
EDIT:
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
解决方案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])
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屋!