wtforms,在构造函数中生成字段 [英] wtforms, generate fields in constructor

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

问题描述

我需要在表单的构造函数中生成字段,因为所需的字段数量可能会有所不同.我认为我当前的解决方案是问题.尝试在模板中用

I need to generate my fields in the constructor of the form since the number of fields needed can vary. I think my current solution is the problem. I get an exception when I try to expand the form in my template saying

AttributeError:"UnboundField"对象没有属性"调用"

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

此代码有什么问题?

class DriverTemplateSchedueForm(Form):
    def __init__(self, per_day=30, **kwargs):
        self.per_day = per_day
        ages = model.Agency.query.all()
        ages = [(a.id, a.name) for a in ages]
        self.days = [[[]] * per_day] * 7
        for d in range(7):
            for i in range(per_day):
                lbl = 'item_' + str(d) + '_' + str(i)
                self.__dict__[lbl] = SelectField(lbl, choices=ages)
                self.days[d][i] = self.__dict__[lbl]
        for day in self.days:
            print(day)

        Form.__init__(self, **kwargs)

推荐答案

修复

您需要将字段添加到您的 class 中,而不是您的 instance 中:

def driver_template_schedue_form(ages, per_day=30, **kwargs):
    """Dynamically creates a driver's schedule form"""

    # First we create the base form
    # Note that we are not adding any fields to it yet
    class DriverTemplateScheduleForm(Form):
        pass

    # Then we iterate over our ranges
    # and create a select field for each
    # item_{d}_{i} in the set, setting each field
    # *on our **class**.
    for d in range(7):
        for i in range(per_day):
            label = 'item_{:d}_{:d}'.format(d, i)
            field = SelectField(label, choices=ages)
            setattr(DriverTemplateScheduleForm, label, field)

    # Finally, we return the *instance* of the class
    # We could also use a dictionary comprehension and then use
    # `type` instead, if that seemed clearer.  That is:
    # type('DriverTemplateScheduleForm', Form, our_fields)(**kwargs)
    return DriverTemplateScheduleForm(**kwargs)

为什么不向 self 添加字段有效?

WTForms使用元类将表单和字段一起注册并保留顺序. * Field 实例是未绑定创建的,添加到 Form 类的 _unbound_fields 属性中,并绑定到类实例

Why doesn't adding fields to self work?

WTForms uses meta-classes to register forms and fields together and preserve order. *Field instances are created unbound, added to the Form class' _unbound_fields attribute and are bound to the class instance when the class is being constructed by the meta-class.

在运行 DriverTemplateScheduleForm .__ init __ 时,已经填充了 _unbound_fields .您可以将您的字段放入 self._unbound_fields ,事情也可以正常工作,但这是使用私有API的,因此以后可能会中断

By the time DriverTemplateScheduleForm.__init__ is run, _unbound_fields has already been populated. You can push your fields into self._unbound_fields and things would also just work, but that's making use of a private API and so may break later.

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

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