【问题标题】:How to distinguish fields and subforms in jinja2?jinja2中如何区分字段和子表单?
【发布时间】:2019-09-30 22:58:12
【问题描述】:

我使用flask_wtf 编写了一个带有表单的Flask 应用程序。我的表单包含字段和子表单。我的目标是使用循环渲染所有字段并自行处理子表单。是否可以区分字段和子表单(在jinja2模板中使用if语句)?

form.py

from flask_wtf import form, FlaskForm
from wtforms import StringField, FieldList, FormField


class MySubform(Form):
    field1 = StringField(label="field1")


class MyForm(Flaskform):
    name = StringField(label="Name")
    subform = FieldList(FormField(MySubform), min_entries=1)

index.html

{% extends "bootstrap/base.html" %}

{% block content %}

<div class="row">
    {% for field in form %}
        <div class="form-group">
            {{ field.label(class_='col-sm-3 control-label') }}
            <div class="col-sm-9">
                {{ field(class_='form-control') }}
            </div>
        </div>        
    {% endfor %}        
</div>
{% endblock %}

【问题讨论】:

    标签: python-3.x jinja2 flask-wtforms


    【解决方案1】:

    index.html

    {% for field in form %}
        {% if field.type == 'FieldList' %}
            // Process Subfields
        {% else %}
            // Process everything except FieldList's
        {% endif %}
    {% endfor %}
    

    【讨论】:

    • 要检查的类型是FormField 否则,代码有效。
    猜你喜欢
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    • 2018-08-15
    • 1970-01-01
    相关资源
    最近更新 更多