treetop
treetop

Reputation: 175

Flask-WTForms- Calling field list entires individually in template

Say if I have a FieldList that contains two fields (but up to a max of 5 allowed entries like so:

class NameForm(Form):
    firstname = StringField('firstname')
    surname = StringField('surname')

class Combine(Form):
    combination = FieldList(FormField(NameForm), min_entries=1, max_entries=5)

If I want to call each entry individually to be displayed in the template I've read I need to call each by it's index.

In my template I've tried calling like so:

{{ form.description.description-0 }}

for wachi I get an error:

TypeError: unsupported operand type(s) for -: 'str' and 'int'

I've also tried the following:

{{ form.combination(index="combination-0") }}

Which does produce the two fields for one of the potential entries in the combination form. However, when I change the number to either 1, 2 3, or 4 (to represent each of the indexes up to the maximum) the displayed on screen entry/index doesn't change as it's still labeled combination-0 in the gui. Am I calling the index correctly or just barking up the wrong tree? Thanks

Upvotes: 1

Views: 938

Answers (1)

Crast
Crast

Reputation: 16326

You want to iterate it most likely:

{% for entry in form.combination %}
    {{ entry.form.firstname }}
    {{ entry.form.surname }}
{% endfor %}

Alternately, if you must get the 2nd entry, you can do

{{ form.combination.entries[1].firstname }}

And the like.

Note that unless there's form data to create more entries, you're going to get an IndexError trying to index nonexistent entries. min_entries=1 only guarantees at least one entry.

If you want to programmatically add entries, use append_entry.

Upvotes: 2

Related Questions