1

after trying for hours I m frustrated with this. I just can't loop over my ChoiceField's choices in the template. It will not even enter the loop. But if I access the form field with pdb it looks fine.

my form:

MODE_CHOICES = (('blue', 'blue'), ('red', 'red'))

class MultiSearchForm(forms.Form):
    mode = forms.ChoiceField(required = True, widget = RadioSelect, choices = MODE_CHOICES)

my view:

class LandingPage(TemplateView):
    template_name = "landingPage.html"

    def get_context_data(self, **kwargs):
        context = super(LandingPage, self).get_context_data(**kwargs)
        context.update({
            'searchForm': MultiSearchForm(),
        })

        return context

my template:

<ul>

{% for choice in searchForm.mode.choices %} // for loop is not entered
  <li>
    <input type="radio" name="mode" value="{{choice.0}}"
      {% ifequal searchForm.mode.data choice.0 %}
        checked="checked"
      {% endifequal %}/>
  </li>
{% endfor %}
</ul

{{searchForm.mode.choices.0}} //no output

{{searchForm.mode}} // gives me 2 radio buttons
4

2 回答 2

2

从 Django 文档(https://docs.djangoproject.com/en/dev/ref/forms/widgets/):

Django 1.4 中的新功能 - 要对生成的标记进行更精细的控制,您可以遍历模板中的单选按钮。假设表单 myform 带有一个使用 RadioSelect 作为其小部件的字段 beatles:

  {% for radio in myform.beatles %}
  <div class="myradio">
      {{ radio }}
  </div>
  {% endfor %}
于 2012-08-07T16:38:32.033 回答
0

你为什么要这样做?您应该让字段自己输出,包括选定的字段。如果您需要设置要选择的选项之一,您应该在视图或表单中进行,使用initial参数:

    context.update({
        'searchForm': MultiSearchForm(initial={'mode': your_choice}),
    })
于 2011-07-10T07:15:04.250 回答