我需要在表单的构造函数中生成字段,因为所需字段的数量可能会有所不同。我认为我目前的解决方案就是这个问题。当我试图扩展模板中的表单时,出现了一个异常
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)
修复
您需要将字段添加到类中,而不是添加到实例中:
为什么向
self
添加字段不起作用?WTForms使用元类将表单和字段一起注册并保持顺序。} class' ^{} attribute ,并绑定到类实例when the class is being constructed by the meta-class。在
*Field
实例创建时没有绑定,added to the ^{当
DriverTemplateScheduleForm.__init__
运行时,_unbound_fields
已经被填充。你可以把你的字段推到self._unbound_fields
中,这样也可以工作,但这是使用私有API,因此以后可能会中断。在关于元类的答案是正确的,但是如果你真的需要这个(像我一样):
请注意,我们不会修改
_unbound_fields
,下次也不会在表单类中包含此字段。在相关问题 更多 >
编程相关推荐