For starters, there's an argument for the FieldList called min_entries
, that will make space for your data:
class CompanyForm(Form):
company_name = StringField('company_name')
locations = FieldList(FormField(LocationForm), min_entries=2)
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:
<form action="" method="post" role="form">
{{ companyForm.hidden_tag() }}
{{ companyForm.company_name() }}
{{ companyForm.locations() }}
<input type="submit" value="Submit!" />
</form>
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
{% for l in companyForms.locations %}
{{ l.form.city }}
{% endfor %}
(in wtforms alone l.city
is shorthand for l.form.city
. However, that syntax seems to clash with Jinja, and there it is necessary to use the explicit l.form.city
in the template.)
Now to ready the submitted data, just create the CompanyForm
and iterate over the locations:
for entry in form.locations.entries:
print entry.data['location_id']
print entry.data['city']
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…