How to use a WTForms FieldList of FormFields?

后端 未结 1 644
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 00:53

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):
    l         


        
相关标签:
1条回答
  • 2020-12-08 01:41

    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']
    
    0 讨论(0)
提交回复
热议问题