且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

动态添加字段到WTForms窗体

更新时间:2022-11-25 22:54:00

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 %}

相关阅读

技术问答最新文章