Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate WTForms FieldList with Jinja2

Tags:

jinja2

wtforms

As the title says, here's what I've got:

form = F(obj = myobject)
myfieldlist= FieldList(FormField(form))

{% for subfield in form.myfieldlist %}
    {{ subfield.field }}
    {{ subfield.label }}
{% endfor %}

This outputs nothing, any ideas? Also, not entirely sure if FormField is required. Thanks

like image 847
bobwal Avatar asked Jun 19 '13 22:06

bobwal


1 Answers

FormField takes a class not an instance:

class GuestForm(Form):
    email = TextField()
    vip = BooleanField()

class VenueForm(Form):
    name = TextField()
    guests = FieldList(FormField(GuestForm))

Then in your controller:

form = VenueForm(obj=myobject)
render("template-name.html", form=form)

In your template you will need to iterate over the FieldList field as if it was its own form:

{% for guest_form in form.guests %}
    <ul>
    {% for subfield in guest_form %}
    <li>{{ subfield.label }} {{ subfield }}</li>
    {% endfor %}
    </ul>
{% endfor %}
like image 121
Sean Vieira Avatar answered Nov 09 '22 12:11

Sean Vieira