如何在 WTForms 中生成动态字段 [英] How do I generate dynamic fields in WTForms

查看:38
本文介绍了如何在 WTForms 中生成动态字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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()

但我收到以下错误:

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

我做错了什么,还是没有办法在 WTForms 中完成这个?

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

推荐答案

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

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

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)

我发现这篇帖子也很有帮助

这篇关于如何在 WTForms 中生成动态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆