python - Flask-WTFoms 字段中的自定义参数

标签 python flask jinja2 flask-wtforms

forms.py

my_field = TextField(u"Enter a number", validators=[Required('This Field is Required')])

my_form.html

<table>
  <tr>
    <td colspan="4"> 
      {{form.my_field(placeholder= form.my_field.label.text, class_="form-control")}}
      {% for error in form.my_field.errors %}
          <span>{{error}}</span>
      {% endfor %}
    </td>
  </tr>
</table>

这是一个简单的代码。但我想遵循this在循环中渲染所有输入字段,而不是为每个输入字段编写代码。但每个字段都会有不同的colspan对应<td>中的值。

如何为 colspan 添加可在 <td> 中使用的自定义参数?

类似:(只是上面代码中的 diff)

forms.py

my_field = TextField(colspan="4")

my_form.html

<td colspan={{form.my_field.colspan}}>

最佳答案

您需要创建一个custom field带有额外的 colspan 属性。

首先定义自定义字段子类TextField:

class MyCustomTextField(TextField):
    def __init__(self, colspan=4, *args, **kwargs):
        super(MyCustomTextField, self).__init__(*args, **kwargs)
        self.colspan = colspan

现在在表单中使用自定义字段:

class MyForm(Form):
    my_field = MyCustomTextField(4, u"Enter a number", validators=[Required('This Field is Required')])

看到 MyCustomTextField 的第一个参数(本例中为 4)了吗?这是你的 colspan 属性。

最后,像这样访问模板中的属性:

<td colspan="{{form.my_field.colspan}}">

关于python - Flask-WTFoms 字段中的自定义参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39544715/

相关文章:

python - Jinja2 API : how to get the inherited template of a template?

javascript - 使用FLASK时使用JS函数更改背景图像

python每秒平均比特率

python - 我有一个 for 循环来创建一个列表,我可以改用列表理解吗?

python - 在 Flask 中处理用户上传的图片

python - 使用 Flask 更新 HTML 字段

python - 将 HTML 插入 Flask 的正确方法

python - 如何从 sqlalchemy 获取元数据以在 jinja 中显示为表格?

python - 如何访问我网站上的MySQL服务器?

python - 如何使用字典设置 Python Pandas Dataframe 的样式