librelist archives

« back to archive

Flask-WTF problems with CSRF and FormField

Flask-WTF problems with CSRF and FormField

From:
Michel Albert
Date:
2012-05-11 @ 14:49
Hi,

I have the following form:

    class DeviceBaseForm(Form):
        hostname = TextField("hostname", validators=[Required()])
        ip_pool = SelectField("IP Pool")
        device_type = TextField("Device Type", validators=[Required()])


    class ETODeviceForm(Form):
        ct = TextField('CT')
        eto_id = TextField('ETO Number')
        model = SelectField('Device Model')


    class CopperDeviceForm(Form):
        isam = TextField('ISAM')


    class DeviceForm(Form):
        base = FormField(DeviceBaseForm)
        eto = FormField(ETODeviceForm)
        copper = FormField(CopperDeviceForm)

        def __init__(self, *args, **kwargs):
            kwargs['csrf_enabled'] = False
            super(DeviceForm, self).__init__(*args, **kwargs)

And the form:

    {#
     # Render a form field, with errors if necessary.
     # @param field: The form field.
     #}
    {% macro render_field(field) %}
        {% if field.type == 'HiddenField' %}
            {{ field(**kwargs)|safe }}
        {% else %}
            <dt>{{ field.label }}</dt>
            <dd>{{ field(**kwargs)|safe }}</dd>
        {% endif %}
        {% if field.errors %}
            <ul class="errors">
                {% for error in field.errors %}<li>{{ field.label }}:
{{ error }}{% endfor %}
            </ul>
        {% endif %}
    {% endmacro %}

    <form method="POST" action="{{url_for('device_base')}}">
        <fieldset>
            <legend>Device Info</legend>
            <dl>
                {{ frag.render_field(form.base.hostname) }}
                {{ frag.render_field(form.base.ip_pool) }}
                {{ frag.render_field(form.base.device_type) }}
            </dl>
        </fieldset>
        <fieldset>
            <legend>ETO</legend>
            <dl>
                {{ frag.render_field(form.eto.ct) }}
                {{ frag.render_field(form.eto.eto_id) }}
                {{ frag.render_field(form.eto.model) }}
            </dl>
        </fieldset>
        <fieldset>
            <legend>Copper</legend>
            <dl>
                {{ frag.render_field(form.copper.isam) }}
            </dl>
        </fieldset>
        <input type="submit" value="Go" />
    </form>


as suggested in another thread

(http://flask.pocoo.org/mailinglist/archive/2010/10/9/flask-wtf-csrf-with-fieldlist/),
I added the "csrf_enabled" override in the form's __init__ code. But I
still get an error about missing or invalid CSRF tokens. Any ideas?