Flask-WTForms- 在模板中单独调用字段列表

Flask-WTForms- Calling field list entires individually in template

假设我有一个包含两个字段的 FieldList(但最多允许 5 个条目,如下所示:

class NameForm(Form):
    firstname = StringField('firstname')
    surname = StringField('surname')

class Combine(Form):
    combination = FieldList(FormField(NameForm), min_entries=1, max_entries=5)

如果我想单独调用每个条目以显示在我读过的模板中,我需要通过它的索引来调用每个条目。

在我的模板中,我试过这样调用:

{{ form.description.description-0 }}

对于 wachi 我得到一个错误:

TypeError:- 的操作数类型不受支持:'str' 和 'int'

我也试过以下方法:

{{ form.combination(index="combination-0") }}

这确实为组合表单中的一个潜在条目生成了两个字段。但是,当我将数字更改为 1、2、3 或 4(以表示每个索引的最大值)时,屏幕上显示的 entry/index 不会改变,因为它仍然标记为 combination-0桂。 我是正确地调用了索引还是只是找错了树? 谢谢

您想迭代它的可能性最大:

{% for entry in form.combination %}
    {{ entry.form.firstname }}
    {{ entry.form.surname }}
{% endfor %}

或者,如果您必须获得第 2 个条目,您可以这样做

{{ form.combination.entries[1].firstname }}

等等。

请注意,除非有表单数据可以创建更多条目,否则您将得到一个 IndexError 试图索引不存在的条目。 min_entries=1只保证至少有一个条目。

如果您想以编程方式添加条目,请使用 append_entry