【问题标题】:Flask-WTForms- Calling field list entires individually in templateFlask-WTForms-在模板中单独调用字段列表
【发布时间】:2017-09-03 11:34:36
【问题描述】:

假设我有一个包含两个字段的 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(以表示每个索引达到最大值)时,屏幕条目/索引上显示的内容不会改变,因为它仍然在 gui 中标记为组合 0。 我是正确调用索引还是只是吠叫错误的树? 谢谢

【问题讨论】:

    标签: python jinja2 wtforms flask-wtforms


    【解决方案1】:

    你最有可能想要迭代它:

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

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

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

    等等。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-05
      • 1970-01-01
      • 2014-07-28
      • 2011-08-25
      • 1970-01-01
      • 1970-01-01
      • 2016-05-05
      • 2020-01-18
      相关资源
      最近更新 更多