开发者

Django ChoiceField: Fail to access choices in template

开发者 https://www.devze.com 2023-03-18 23:25 出处:网络
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

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}),
    })
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号