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 开发者_JAVA技巧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
From the Django documentation (https://docs.djangoproject.com/en/dev/ref/forms/widgets/):
New in Django 1.4 - For more granular control over the generated markup, you can loop over the radio buttons in the template. Assuming a form myform with a field beatles that uses a RadioSelect as its widget:
{% for radio in myform.beatles %}
<div class="myradio">
{{ radio }}
</div>
{% endfor %}
Why are you doing it like this? You should let the field output itself, including the selected field. If you need to set one of the choices to be selected, you should do it in the view or the form, with the initial
parameter:
context.update({
'searchForm': MultiSearchForm(initial={'mode': your_choice}),
})
精彩评论