WTForms-flask:将表单字段名称和数据组织到字典中

时间:2018-10-03 20:25:16

标签: dictionary for-loop flask flask-wtforms wtforms

我已经坚持了一段时间:

我有这样的表格:

class attributes(Form):
    height=IntegerField('height')
    weight=IntegerField('weight')

class main(Form):
    John=FormField(attributes)
    Ted=FormField(attributes)
    David(FormField(attributes)`

我希望迭代创建一个字典,以在烧瓶中存储标识字段标签和字段数据,而无需为每个FormField使用John_height=John.height.data。想法是最终使用SQL语句传递字典以将其写入数据库,其中字典键将匹配数据库列,而formfield数据将成为数据库值。

字典应该看起来像这样:

{John_height : 170,
John_weight: 170,
Ted_height : 120,
Ted_weight: 190,
David_height : 150,
David_weight: 100}

谢谢。

1 个答案:

答案 0 :(得分:1)

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值归因于空白表单的构建。