在WTForms中访问RadioField的子字段

时间:2014-04-06 04:55:32

标签: python radio-button wtforms flask-wtforms

建议的模板HTML无线电输入建模方法是:

{% for subfield in form.radio %}
<tr>
    <td>{{ subfield }}</td>
    <td>{{ subfield.label }}</td>
</tr>
{% endfor %}

但如果我在无线电子域之间有一些元素怎么办?我想做这样的事情:

{{ form.radio[0] }} {{ form.radio[0].label }}
<div>Something 1</div>
<div>Something 2</div>
<div>Something 3</div>
{{ form.radio[1] }} {{ form.radio[1].label }}
<div>Something 4</div>
{{ form.radio[2] }} {{ form.radio[2].label }}

有没有办法像这样访问子文件?

1 个答案:

答案 0 :(得分:2)

将其转换为列表,您就可以了。

In [1]: import wtforms
In [2]: class Form(wtforms.form.Form):
   ...:         radio = wtforms.fields.RadioField(choices=((1, 1), (2, 2)))
   ...:
In [3]: f = Form()
In [4]: option1, option2 = f.radio
In [5]: print option1
<input id="radio-0" name="radio" type="radio" value="1">
In [6]: print option2
<input id="radio-1" name="radio" type="radio" value="2">
In [7]: opts = list(f.radio)
In [8]: print opts[0]
<input id="radio-0" name="radio" type="radio" value="1">
In [9]: print opts[1]
<input id="radio-1" name="radio" type="radio" value="2">