2012-05-08 52 views
2

我有這樣的事情:使用價值

forms.py:

AVATAR_CHOICES = (('1','option1'), ('2','option2'), ('3','option3'), 
('4','option4')) 

class RegistrationForm(forms.Form): 
    avatar = ChoiceField(widget=RadioSelect, choices=AVATAR_CHOICES) 

我傳遞form從我的觀點:

views.py

form = RegistrationForm() 
return render_to_response('registration/register.html', {'form': form}, 
          context_instance=RequestContext(request)) 

進入如下模板:

registration.html:

{% for radio in form.avatar %} 
    <label class="radio">{{ radio.tag }}</label> 
{% endfor %} 

,但我想包括在這些選項字段的前方圖像,以此來讓用戶選擇一個頭像。但是,我不知道如何訪問元組AVATAR_CHOICES中的鍵或值。主要想法是能夠做到這樣的事情:

{% for radio in form.avatar %} 
     <label class="radio">{{ radio.tag }}</label> 
     <img src="{{ STATIC_URL }}img/avatars/{{ radio.tag.value }}.jpg"/> 
{% endfor %} 

我該怎麼做?

在此先感謝。

+0

@ IgnacioVazquez-Abrams該問題適用於有選擇的模型字段,而這個問題適用於表單字段。 AFAIK表單字段沒有相應的'get_XXX_display',如果有的話,它是(a)不同的事情,(b)在這裏如何處理它並不明顯。 – Dougal

+0

哈。在這裏,我總是指責別人不讀這個問題(不是說我總是*錯*,請介意你......)。 –

回答

6

你可以嘗試

{{ radio.choice_value }}{# value of the choice of the current input #} 
{{ radio.choice_label }}{# label of the choice of the current input #} 
{{ radio.choice_index }}{# 0-based index #} 

只有choice_labelgets documented,但你可以安全地使用它爲止。