wtforms,在构造函数中生成字段

cha*_*255 2 python jinja2 flask wtforms

我需要在表单的构造函数中生成我的字段,因为所需的字段数可能会有所不同.我认为我目前的解决方案是问题所在.当我尝试在模板中展开表单时,我得到一个例外

AttributeError:'UnboundField'对象没有属性' 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)
Run Code Online (Sandbox Code Playgroud)

Sea*_*ira 7

修复

您需要将字段添加到您的而不是您的实例:

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)
Run Code Online (Sandbox Code Playgroud)

为什么不添加字段self

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

到时候DriverTemplateScheduleForm.__init__运行,_unbound_fields已经填充了.你可以把你的字段推进去self._unbound_fields,事情也可以正常工作,但那是在使用私有API,因此可能会破坏.