迭代嵌套的FormField

时间:2015-02-03 17:12:07

标签: python flask jinja2 wtforms flask-wtforms

我正在尝试遍历Formfield中的FormField,它们都是FieldList的一部分。

在我的views.py我要求mainForm,模板通过FormField subForm成功迭代。但是,当我无法通过subSubForm进行迭代时。这些字段永远不会出现在浏览器中。

Formcode:

class subSubForm(Form):
    step = IntegerField("step", validators=[NumberRange(min=0, max=99)])
    description = TextField("Description")
    information = TextAreaField("Information Exchanged")])

class subForm(Form):
    name = TextField("Description")
    step = FieldList(FormField(subSubForm), min_entries=1)

class mainForm(Form):
   sub_form = FieldList(FormField(subForm), min_entries=1)

和Jinja2模板:

{% for sub_form in form.sub_form %}
      {{ sub_form.form.name(placeholder='Scenario Title') }}
      {% for error in name %}
             {{error}}
      {% endfor %}

      {% for step in form.sub_form %}
            {{ step.form.id(placeholder='#') }}  
            {{ step.form.description(placeholder='description') }}
            {{ step.form.information(placeholder='info xch') }}
       {% endfor %}
   {% endfor %}
{% endfor %}

以上仅显示sub_form.form.name字段。 如何进行嵌套迭代以便显示step字段?

1 个答案:

答案 0 :(得分:2)

看起来你在模板中的第二个嵌套循环中犯了错误。这是它的固定版本:

{% for sub_form in form.sub_form %}
      {{ sub_form.form.name(placeholder='Scenario Title') }}
      {% for error in name %}
             {{error}}
      {% endfor %}

      {% for step in sub_form.step %}
            {{ step.form.step(placeholder='#') }}  
            {{ step.form.description(placeholder='description') }}
            {{ step.form.information(placeholder='info xch') }}
      {% endfor %}
{% endfor %}

这将呈现:

<input id="sub_form-0-name" name="sub_form-0-name" placeholder="Scenario Title" type="text" value="">
<input id="sub_form-0-step-0-step" name="sub_form-0-step-0-step" placeholder="#" type="text" value="">  
<input id="sub_form-0-step-0-description" name="sub_form-0-step-0-description" placeholder="description" type="text" value="">
<textarea id="sub_form-0-step-0-information" name="sub_form-0-step-0-information" placeholder="info xch"></textarea>