动态添加字段到WTForms窗体 [英] Add fields dynamically to WTForms form

查看:456
本文介绍了动态添加字段到WTForms窗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用基于字典 name:label 的字段来定义一个表单类。我尝试了以下,几乎工作。然而,渲染模板中的字段给了 AttributeError:'UnboundField'对象没有属性'__call __'。如何动态地添加字段到表单?

$ $ p $ $ $ $ c $ def build_form
ContactForm(FlaskForm ):
name = StringField(name)
fieldlist = {}
$ b为key,record.items()中的值:
fieldlist [key] = StringField key)

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

if request.method =='POST':
return'表单处理'

返回render_template('cardcompare.tpl',record = record,表格=表格)



 < ; form method = post> 
{{form.name()}}
{%key,record.items()%}
{{form.fieldlist [key]()}}
{%endfor%}
< input type = submit value = Register>
< / form>


解决方案使用 setattr 添加新的字段作为表单类的属性。这将导致WTForms正确地设置字段,而不是保留未绑定的字段。

$ $ $ $ $ $ $ $ $ $#$带有静态字段的表单类
class MyForm(FlaskForm):
name = StringField('static field')

record = {'field1':'label1','field2':'label2'}

#添加动态字段
for key,value in record.items():
setattr(MyForm,key,StringField(value))

在模板中,您可以使用 attr 过滤器遍历字段。

  {关键字的值,record.items()中的值%}:
{{form | attr(key)()}}
{%endfor%}


I want to define a form class with fields based on a dict of name: label. I tried the following, which nearly worked. However, rendering the fields in a template gave AttributeError: 'UnboundField' object has no attribute '__call__'. How can I dynamically add fields to a form?

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>

解决方案

Use setattr to add new fields as attributes of the form class. This will cause WTForms to set up the field correctly instead of keeping the unbound field.

# 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))

In the template you can iterate over the fields using the attr filter.

{% for key, value in record.items() %}:
    {{ form|attr(key)() }}
{% endfor %}

这篇关于动态添加字段到WTForms窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆