Iterating over submitted form fields in Flask?


Question

In Flask 0.8, I know I can access individual form fields using form.fieldname.data, but is there a simple way of iterating over all the form fields? I'm building an email message body, and I'd like to loop over all the fields and create a fieldname/value entry for each, as opposed to manually building it by naming each field and appending.

1
13
10/15/2011 12:35:25 PM

Accepted Answer

I suspect that your are using WTForms.

You can iterate over form data:

for fieldname, value in form.data.items():
    pass

You can iterate over all form fields:

for field in form:
    # these are available to you:
    field.name
    field.description
    field.label.text
    field.data
29
6/10/2014 8:40:00 AM

The form object has an iterator defined on it:

{% for field in form %}
    <tr>
    {% if field.type == "BooleanField" %}
        <td></td>
        <td>{{ field }} {{ field.label }}</td>
    {% else %}
        <td>{{ field.label }}</td>
        <td>{{ field }}</td>
    {% end %}
    </tr>
{% endfor %}

This is from http://wtforms.simplecodes.com/docs/0.6/fields.html


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon