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>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…