ModelChoiceField ,删除空白选项 [英] ModelChoiceField , removing the blank choice
问题描述
我想摆脱-------------"选择 Django 在一个代表 ModelForm 上的外键的选择输入中添加
I want to get rid of the "-------------" choice Django adds in a select input representing a Foreign Key on a ModelForm
已经回答,您可以使用 empty_label=none
选项,但我有一个 ModelForm,而不是常规表单,并且不允许覆盖该字段.
It's been answered that you can use the empty_label=none
option, but I have a ModelForm, not a regular form and overriding the field is not allowed.
我知道我可以覆盖 ModelForm 的 __init__()
方法,以便使用
I know that I can override the __init__()
method of the ModelForm in order to modify a ModelChoiceField's queryset using
self.fields['my_foreign_key'].queryset = ....
但这真的很难看,因为这在主"模型上发生了超过 10 个外键,而且基于该模型的 Modelform 还不止一个
But this would be really ugly, as this happens over +10 foreign_keys on the "Main" model, and there's more than a Modelform based on this model
整个上下文:
- 这些外键中的每一个都指向同一种模型:它们是特定的选择列表,许多模型可以通过管理员轻松修改.
- 所有这些模型都通过to_field=code"关系与主模型相关,基于包含三字母代码的 Charfield(嘿,不是我的错,我不得不使用旧的 MS Access DB),这个 CharField 有
blank=True, unique=True
选项,所以我可以为每个列表创建一个"---No information yet---"
记录,其中有,你打赌,一个空白值而不是三个字母的代码......
- each one of these foreign_key points to the same kind of models : they are particular lists of choices, many models to ease their modification via the admin.
- all these models are related to the Main model via a "to_field=code" relation, based on a Charfield which contains a three-letter code (hey, not my fault, I had to use a legacy MS Access DB), this CharField has the
blank=True, unique=True
options, so I could, for each list, create a"---No information yet---"
record which has, you bet, a blank value instead of a three letter code...
现在的情况是:我得到一个带有两个空白值"选项的选择输入字段:django 一个和我的,一个接一个.我也只是在这里错过了一个 'empty_label=none` 选项......
The situation is now : I get a select input field with two "blank value" choices : the django one and mine, one after the other. I just miss a 'empty_label=none` option here too...
推荐答案
如果您想删除所有 ModelChoiceField
的空白选项,您可以执行以下操作..
If you want to remove the blank choice for all ModelChoiceField
you could do something like..
class Form(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(Form, self).__init__(*args, **kwargs)
modelchoicefields = [field for field_name, field in self.fields.iteritems() if
isinstance(field, forms.ModelChoiceField)]
for field in modelchoicefield:
field.empty_label = None
但那会取代所有的 ModelChoiceField
,所以也许更细粒度的东西:
But that would replace all ModelChoiceField
s, so maybe something more fine grained like:
for fieldname in ('field1','field2','field3','field4','field5','field6'):
self.fields[fieldname].empty_label = None
当然比你提到的 __init__
覆盖更容易!
Certainly easier than the __init__
overwrite you mentioned!
您可以使用 2017+ 使用:
You can use 2017+ use:
forms.ModelChoiceField(... empty_label=None
这篇关于ModelChoiceField ,删除空白选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!