一尘不染

如何在WTForms中生成动态字段

flask

我正在尝试根据此文档http://wtforms.simplecodes.com/docs/1.0.2/specific_problems.html#dynamic-form-composition在WTForms中生成具有动态字段的表单

我有这个子窗体类,它允许用户从列表中选择要购买的物品:

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

class F(Form):
        pass

购物商品将有多个类别,因此我想根据用户选择的类别生成一个动态选择字段:

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

但出现以下错误:

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

我是在做错什么,还是在WTForms中没有办法做到这一点?


阅读 488

收藏
2020-04-06

共1个答案

一尘不染

今晚我遇到了这个问题,并最终解决了这个问题。我希望这对将来的人有帮助。

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)
2020-04-06