将字段动态添加到WTForms表单

时间:2017-05-09 02:16:19

标签: python flask wtforms flask-wtforms

我想根据name: label的字典定义一个包含字段的表单类。我尝试了以下几乎有效的方法。但是,渲染模板中的字段会产生AttributeError: 'UnboundField' object has no attribute '__call__'。如何动态地向表单添加字段?

def build_form(name, record):
    class ContactForm(FlaskForm):
        name = StringField(name)
        fieldlist = {}

        for key, value in record.items():
            fieldlist[key] = StringField(key)

    @app.route('/', methods=['GET', 'POST'])
    def showform():
        form = ContactForm(request.form)

        if request.method == 'POST':
            return 'form processed'

        return render_template('cardcompare.tpl', record=record, form=form)
<form method=post>
    {{ form.name() }}
    {% for key, value in record.items() %}
        {{ form.fieldlist[key]() }}
    {% endfor %}
    <input type=submit value=Register>
</form>

1 个答案:

答案 0 :(得分:4)

使用You need to change them into 2-D arrays: import numpy as np np.array([1,2,3,4]).shape --(4,) np.array([1,2,3,4]).reshape(-1,1).shape --(4,1) np.array([1,2,3,4]).reshape(1,-1).shape --(1,4) 添加新字段作为表单类的属性。这将导致WTForms正确设置字段,而不是保留未绑定字段。

setattr

在模板中,您可以使用# form class with static fields class MyForm(FlaskForm): name = StringField('static field') record = {'field1': 'label1', 'field2': 'label2'} # add dynamic fields for key, value in record.items(): setattr(MyForm, key, StringField(value)) 过滤器迭代字段。

attr