【问题标题】:Render WTF FieldList of SelectFields with Bootstrap使用 Bootstrap 渲染 SelectFields 的 WTF 字段列表
【发布时间】:2019-10-24 03:32:20
【问题描述】:

我想用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 %}

【问题讨论】:

    标签: python flask flask-wtforms flask-bootstrap


    【解决方案1】:

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

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

    但是,SelectField 的标签不是字符串,而是包含字符串变量 text 的对象。将上述代码行替换为

    selectfield.label.text = "some_string"
    

    完成了任务。

    【讨论】:

      猜你喜欢
      • 2015-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-14
      • 1970-01-01
      相关资源
      最近更新 更多