How do I generate dynamic fields in WTForms

ChiliConSql picture ChiliConSql · Oct 12, 2012 · Viewed 25.8k times · Source

I am trying to generate a form in WTForms that has dynamic fields according to this documentation http://wtforms.simplecodes.com/docs/1.0.2/specific_problems.html#dynamic-form-composition

I have this subform class which allows users to pick items to purchase from a list:

class Item(Form):
    itmid = SelectField('Item ID')
    qty = IntegerField('Quantity')

class F(Form):
        pass

There will be more than one category of shopping items, so I would like to generate a dynamic select field based on what categories the user will choose:

fld = FieldList(FormField(Item))
fld.append_entry()

but I get the following error:

AttributeError: 'UnboundField' object has no attribute 'append_entry'

Am I doing something wrong, or is there no way to accomplish this in WTForms?

Answer

Matt Carrier picture Matt Carrier · May 6, 2013

I ran into this issue tonight and ended up with this. I hope this helps future people.

RecipeForm.py

class RecipeForm(Form):
    category = SelectField('Category', choices=[], coerce=int)
    ...

views.py

@mod.route('/recipes/create', methods=['POST'])
def validateRecipe():
    categories = [(c.id, c.name) for c in g.user.categories.order_by(Category.name).all()]
    form = RecipeForm(request.form)
    form.category.choices = categories
    ...

@mod.route('/recipes/create', methods=['GET'])
def createRecipe():
    categories = [(c.id, c.name) for c in g.user.categories.order_by(Category.name).all()]
    form = RecipeForm(request.form)
    form.category.choices = categories
    return render_template('recipes/createRecipe.html', form=form)

I found this post helpful as well