Django ChoiceField:无法访问模板中的选择
尝试了几个小时后我对此感到沮丧。我只是无法循环遍历模板中 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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自 Django 文档 (https://docs.djangoproject.com/en/dev /ref/forms/widgets/):
Django 1.4 中的新增功能 - 为了更精细地控制生成的标记,您可以循环遍历模板中的单选按钮。假设一个表单 myform 带有一个使用 RadioSelect 作为其小部件的字段 Beatles:
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:
你为什么要这样做?您应该让字段自行输出,包括所选字段。如果您需要设置要选择的选项之一,您应该在视图或表单中使用
initial
参数进行操作: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: