2012-04-03 78 views
7

我試圖找到一種顯示多選字段的選定/初始值的文本的方式。Django:顯示模板中選定的多選字段的值

我的問題是類似這樣的,除了我不想我想它對應的選項文本:

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語句(即「如果key ==‘男’‘男人’......等」)

+1

這很可能是這樣的:'{%關鍵在form.genders.value%} {{form.genders.get_key_display}} {%endfor%}'但我不確定。 – Mig 2012-04-03 13:33:12

回答

6
  1. 的方法添加到窗體,返回要

  2. 從模板

說它列表

它看起來像這樣:

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 %} 
+0

感謝您的回覆。有什麼辦法可以把它變成一個模板標籤或什麼?我有相當多的領域,我需要做到這一點,並不真的想每個領域的方法... – John 2012-04-03 14:08:21

+1

你應該做一個模板過濾器,而不是更容易。 – jpic 2012-04-03 14:09:45

+0

好的,我會去的。謝謝 – John 2012-04-03 14:13:02

相關問題