gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:42:17 25 4
gpt4 key购买 nike

我需要在表单的构造函数中生成我的字段,因为所需字段的数量可能会有所不同。我认为我目前的解决方案是问题所在。当我尝试在我的模板中扩展表单时出现异常

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)

最佳答案

修复

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

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 实例未绑定(bind)创建,added to the Form class' _unbound_fields attribute并绑定(bind)到类实例 when the class is being constructed by the meta-class .

DriverTemplateScheduleForm.__init__ 运行时,_unbound_fields 已经被填充。您可以将您的字段推送到 self._unbound_fields 中,事情也将正常工作,但这是使用私有(private) API,因此稍后可能会中断.

关于python - wtforms,在构造函数中生成字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31160781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com