2

我有这样的事情:

表格.py:

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

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

form从我的观点经过:

视图.py

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

变成这样的模板:

注册.html:

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

但我想在这些选项字段前面包含图像,作为让用户选择头像的一种方式。但是,我不知道如何从 tuple 访问键或值AVATAR_CHOICES。主要思想是能够做这样的事情:

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

我怎样才能做到这一点?

提前致谢。

4

1 回答 1

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_label 记录在案,但到目前为止您可以安全地使用它。

于 2012-05-08T14:34:45.930 回答