我已经被困在这个问题上有一段时间了:
我有一个像这样的表格:
class attributes(Form):
height=IntegerField('height')
weight=IntegerField('weight')
class main(Form):
John=FormField(attributes)
Ted=FormField(attributes)
David(FormField(attributes)`
我希望迭代创建一个字典来在 flask 中存储标识字段标签和字段数据,而不为每个 FormField 使用 John_height=John.height.data
。这个想法是最终使用 SQL 语句传递字典以写入数据库,其中字典键将与数据库列匹配,表单字段数据将是数据库值。
字典应该看起来像这样:
{John_height : 170,
John_weight: 170,
Ted_height : 120,
Ted_weight: 190,
David_height : 150,
David_weight: 100}
提前谢谢您。
最佳答案
from wtforms import Form
from wtforms.fields import IntegerField, FormField
class Attributes(Form):
height = IntegerField('height')
weight = IntegerField('weight')
要迭代构建表单,您可以执行以下任一操作:
def main(people=['John', 'Ted', 'David']):
class Main(Form):
pass
for person in people:
setattr(Main, person, FormField(Attributes))
return Main()
或
class Main(Form):
for person in ['John', 'Ted', 'David']:
vars()[person] = FormField(Attributes)
del person
我个人更喜欢第二种,因为它是一个适当的类结构,但动态性较差。
要构建字典,您可以执行以下操作:
obj = Main()
data = dict()
for field in obj: # <- this works since obj has an __iter__ method self defined
for key in field.data.keys():
data.update({field.name + '_' + key: field.data[key]})
print(data)
>>> {'John_height': None, 'John_weight': None, 'Ted_height': None, 'Ted_weight': None, 'David_height': None, 'David_weight': None}
None
值是由于空表单构造造成的。
关于dictionary - WTForms- flask : organize formfield name and data into dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52635146/