I'm building a website using Flask in which I use WTForms. In a Form I now want to use a FieldList of FormFields as follows:
class LocationForm(Form):
location_id = StringField('location_id')
city = StringField('city')
class CompanyForm(Form):
company_name = StringField('company_name')
locations = FieldList(FormField(LocationForm))
so to give people the ability to enter a company with two locations (dynamic adding of locations comes later) I do this on the front side:
<form action="" method="post" role="form">
{{ companyForm.hidden_tag() }}
{{ companyForm.company_name() }}
{{ locationForm.location_id() }}
{{ locationForm.city() }}
{{ locationForm.location_id() }}
{{ locationForm.city() }}
<input type="submit" value="Submit!" />
</form>
So on submit I print the locations:
print companyForm.locations.data
but I get
[{'location_id': u'', 'city': u''}]
I can print the values of the first location using the locationForm (see below), but I still don't know how to get the data of the second location.
print locationForm.location_id.data
print locationForm.city.data
So the list of locations does have one dict with empty values, but:
- Why does the list of locations have only one, and not two dicts?
- And why are the values in the location dict empty?
Does anybody know what I'm doing wrong here? All tips are welcome!
For starters, there's an argument for the FieldList called
min_entries
, that will make space for your data:This will setup the list the way you need. Next you should render the fields directly from the
locations
property, so names are generated correctly:Look at the rendered html, the inputs should have names like
locations-0-city
, this way WTForms will know which is which.Alternatively, for custom rendering of elements do
(in wtforms alone
l.city
is shorthand forl.form.city
. However, that syntax seems to clash with Jinja, and there it is necessary to use the explicitl.form.city
in the template.)Now to ready the submitted data, just create the
CompanyForm
and iterate over the locations: