使用 Bootstrap 渲染 SelectFields 的 WTF FieldList

Render WTF FieldList of SelectFields with Bootstrap

我想用 bootstrap/wtf.html 呈现 flask_wtf 表单。 该表单包含一个常规的 SelectField 和一个 FieldList 的 SelectFields。 使用函数 wtf.form_field 可以很好地渲染单个 SelectField。 但是,对 FieldList 的每个 SelectField 应用相同的函数会引发错误:

  File "/usr/local/lib/python3.5/dist-packages/flask_bootstrap/templates/bootstrap/wtf.html", line 119, in template
    {{field.label(class="control-label")|safe}}
TypeError: 'str' object is not callable

我对该错误的解释是,字符串 "field.label" 的调用方式类似于使用括号的函数。另一方面,这似乎也适用于单个 SelectField。

这里是form.py:

from flask_wtf import FlaskForm
from wtforms import SelectField, FieldList, FormField

class FormEntry(FlaskForm):
    selectfield = SelectField('Name', coerce=int)

class MyForm(FlaskForm):
    selectfield = SelectField('Name', coerce=int, choices=[(2, "choice 2"), (1, "choice 1")])
    form_entries = FieldList(FormField(FormEntry))

这里是 render.html:

 {% extends 'bootstrap/base.html' %}
 {% import 'bootstrap/wtf.html' as wtf %}

 {{ form.hidden_tag() }}
 {{ wtf.form_field(form.selectfield) }}
 {% for entry in form.form_entries %}
     {{ wtf.form_field(entry.selectfield) }}
 {% endfor %}

我找到了错误来源。 在我的脚本中,我通过

动态分配了 FormEntry 的选择字段的标签
selectfield.label = "some_string"

然而,SelectField 的标签不是一个字符串,而是一个包含字符串变量text 的对象。将上面这行代码替换为

selectfield.label.text = "some_string"

完成任务。