machump
machump

Reputation: 1267

WTForms-flask: organize formfield name and data into dictionary

I've been stuck on this for some time now:

I have a form like so:

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

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

I wish to iteratively create a dictionary to store an identifying field label and field data in flask without using John_height=John.height.data for every FormField. The idea is to eventually pass the dictionary for writing into a database using a SQL statement where the dictionary key will match the database column and formfield data will be the database values.

The dictionary should look something like this:

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

Thank you in advance.

Upvotes: 2

Views: 1486

Answers (1)

Attack68
Attack68

Reputation: 4765

from wtforms import Form
from wtforms.fields import IntegerField, FormField

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

To build your forms iteratively you can do either of these:

def main(people=['John', 'Ted', 'David']):
    class Main(Form):
        pass
    for person in people:
        setattr(Main, person, FormField(Attributes))
    return Main()

or

class Main(Form):
    for person in ['John', 'Ted', 'David']:
        vars()[person] = FormField(Attributes)
    del person

personally I prefer the second since it is a proper class structure but less dynamic.

To build your dictionary you can then do the following:

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}

The None values are due to empty form construction.

Upvotes: 4

Related Questions