更新时间: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 %}