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

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

问题描述

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



我有这个子类允许用户从列表中选择要购买的项目:

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

class F(Form):
pass

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

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

但我得到以下错误:

  AttributeError:'UnboundField'对象有没有属性'append_entry'

我做错了什么,还是没有办法在WTForms ?

解决方案

def append_field(cls,name,field):
setattr(cls,name,field)
返回cls

从窗体导入TestForm
form = TestForm.append_field( do_you_want_fries_with_that,BooleanField('fries'))(obj = db_populate_object)

我使用扩展类 BaseForm 为所有我的形式,并在类上有一个方便的append_field函数。

返回字段附加类,因为实例)不能附加字段。


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?

解决方案

class BaseForm(Form):
    @classmethod
    def append_field(cls, name, field):
        setattr(cls, name, field)
        return cls

from forms import TestForm
form = TestForm.append_field("do_you_want_fries_with_that",BooleanField('fries'))(obj=db_populate_object)

I use the extended class BaseForm for all my forms and have a convenient append_field function on class.

Returns the class with the field appended, since instances (of Form fields) can't append fields.

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

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