我正在尝试找到一种显示多选字段所选/初始值文本的方法。
我的问题类似于这个问题,除了我不想值我想要它对应的选项文本:
Display value of a django form field in a template?
例如,如果我有一个包含以下内容的表单:
GENDER_CHOICES = (
('male', _('Men')),
('female', _('Women')),
)
genders = forms.MultipleChoiceField(choices=GENDER_CHOICES,
widget=widgets.CheckboxSelectMultiple(),
initial=[gender[0] for gender in GENDER_CHOICES])
然后在我的模板中我可以做到:
{{ form.genders.value }}
获取一系列选定的选项(即[u'male',u'female']。但是,我想知道从键中查找字符串值(即“男人”,“女人”),某事像:
{% for key in form.genders.value %}
{{ form.genders.choices.key }}
{% endfor %}
我无法找到一种方法来完成这项工作。如何使用Django 1.3实现这一目标?
ps - 这是一个简短的例子,但是我需要使用更大的动态列表来禁止使用多个if语句(即“if key =='male''Men''等等)
答案 0 :(得分:6)
向表单添加方法,返回您想要的列表
从模板中调用
看起来像这样:
def selected_genders_labels(self):
return [label for value, label in self.fields['genders'].choices if value in self['genders'].value()]
行动中:
In [1]: from testapp.views import XForm; f = XForm(initial={'genders': ['male', 'female']}); print f.selected_genders_labels()
['Men', 'Women']
In [2]: from testapp.views import XForm; f = XForm(initial={'genders': ['female']}); print f.selected_genders_labels()
['Women']
In [3]: from testapp.views import XForm; f = XForm(initial={'genders': []}); print f.selected_genders_labels()
[]
In [4]: from testapp.views import XForm; f = XForm(); print f.selected_genders_labels()
['Men', 'Women']
所以你可以像这样迭代:
{% for label in form.selected_genders_labels %}{{ label }}{% endfor %}
FTR,我用过:
class XForm(forms.Form):
GENDER_CHOICES = (
('male', 'Men'),
('female', 'Women'),
)
genders = forms.MultipleChoiceField(choices=GENDER_CHOICES,
widget=widgets.CheckboxSelectMultiple(),
initial=[gender[0] for gender in GENDER_CHOICES])
def selected_genders_labels(self):
return [label for value, label in self.fields['genders'].choices if value in self['genders'].value()]
您可以制作这样的模板过滤器:
@register.filter
def selected_labels(form, field):
return [label for value, label in form.fields[field].choices if value in form[field].value()]
用法:
{% for label in form|selcted_labels:"genders" %}
{{ label }}
{% endfor %}