8

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> 

1 Answer 1

13

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 %} 
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks, is there a way though to get the dynamic fields added to a structure which can be iterated through in the template? (e.g. like fieldlist in the example)? The goal is to handle the dynamic fields differently than the static in the template.
That part was deleted a litte overeagerly by an edit. I recoverd it.
I've done the same by putting setattr inside __init__ of MyForm , because i need to pass attribute list to the form, it works except the first time running, do you know why?
You need to add these fields to the class, not the instance. This means, before calling MyForm().
@Feodoran i already added to the class but it only work since second form submit. Please take a look at my question here: stackoverflow.com/questions/2583620/…
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.