Suppose I have a form like so:
Toys= FieldList(TextField('what toys do you have?'),min_entries=5)
Fruits= FieldList(TextField('what fruits do you have?'),min_entries=5)
Jewelry= FieldList(TextField('what jewelries do you have?'),min_entries=5)
Candy= FieldList(TextField('what candies do you have?'),min_entries=5)
without explicitly defining the submitted values like
Toy1=form.Toys[1].data
, how might I aggregate all the FieldList data in a form submission for writing into a SQL table like so:?
Toys | Fruits | Jewelry | Candy
ball apple Necklace M&Ms
stick orange Bracelet skittles
top grapes tie clip lollipop
For the sake of simplicity, I've set min_entries=5
for all fields. I tried using a for loop to append column names and values into a dictionary and writing it into my database like so:
field_dict=dict()
for f in form:
if str(f.type) in ['FieldList']:
for x in range(1,5):
field_dict.update({f.name:f.data[x]})
sql_insert="INSERT INTO tablename ({}) values ({})".format(
",".join(field_dict.keys()),
",".join('"' + str(value) + '"' for value in field_dict.values()))
c.execute(sql_insert)
However, it's writing into the database everytime it encounters a Fieldlist
, resulting in a table like:
Toys | Fruits | Jewelry | Candy
ball NULL NULL NULL
ball apple NULL NULL
ball apple Necklace NULL
ball apple Necklace M&Ms