How do I generate dynamic fields in WTForms

前端 未结 6 2225
花落未央
花落未央 2020-12-08 16:06

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-fo

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 16:34

    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

提交回复
热议问题