1

何時間も試した後、私はこれに不満を感じています。テンプレートで ChoiceField の選択肢をループすることはできません。ループにも入らない。しかし、pdb でフォーム フィールドにアクセスすると問題ないように見えます。

私のフォーム:

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

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

私の見解:

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

私のテンプレート:

<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 の新機能 - 生成されたマークアップをより細かく制御するために、テンプレートのラジオ ボタンをループできます。RadioSelect をウィジェットとして使用するフィールド Beatles を持つフォーム myform を想定します。

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

なんでこんなことしてんの?選択したフィールドを含め、フィールド自体を出力させる必要があります。選択肢の 1 つを選択するように設定する必要がある場合は、ビューまたはフォームで次のinitialパラメーターを使用して設定する必要があります。

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