WTForms getting the errors
Asked Answered
G

4

35

Currently in WTForms to access errors you have to loop through field errors like so:

for error in form.username.errors:
        print error

Since I'm building a rest application which uses no form views, I'm forced to check through all form fields in order to find where the error lies.

Is there a way I could do something like:

for fieldName, errorMessage in form.errors:
        ...do something
Gesualdo answered 24/6, 2011 at 3:31 Comment(0)
F
47

The actual form object has an errors attribute that contains the field names and their errors in a dictionary. So you could do:

for fieldName, errorMessages in form.errors.items():
    for err in errorMessages:
        # do something with your errorMessages for fieldName
Fere answered 24/6, 2011 at 17:1 Comment(0)
W
41

A cleaner solution for Flask templates:

Python 3:

{% for field, errors in form.errors.items() %}
<div class="alert alert-error">
    {{ form[field].label }}: {{ ', '.join(errors) }}
</div>
{% endfor %}

Python 2:

{% for field, errors in form.errors.iteritems() %}
<div class="alert alert-error">
    {{ form[field].label }}: {{ ', '.join(errors) }}
</div>
{% endfor %}
Wholehearted answered 17/12, 2013 at 20:58 Comment(4)
This is the best effort on this page. But it looks like somebody took a crap on my form. Exposes the form names too, for my end-users to figure out what cli_tel actually is... Though I might be the only one that cares?Jessejessee
@PeterLada: that's the stupid thing... the errors variable doesn't really provide that. You can do it with something like this I think: form[field].nameWholehearted
If you use python3, use items() instead of iteritems()Uta
instead of using just label. Use label.text. ie: flash(''.join([f'{form[f].label.text}: {"".join(e)} ' for f, e in form.errors.items()])). Removes the html.Patent
H
23

For anyone looking to do this in Flask templates:

{% for field in form.errors %}
{% for error in form.errors[field] %}
    <div class="alert alert-error">
        <strong>Error!</strong> {{error}}
    </div>
{% endfor %}
{% endfor %}
Heretofore answered 20/2, 2013 at 20:44 Comment(0)
B
3

With ModelFormFields in SqlAlchemy when used with WTForms, if you have a nested object inside an object (foreign key relationships), here is how you show the relevant errors for fields properly.

Python side:

def flash_errors(form):
    for field, errors in form.errors.items():
        if type(form[field]) == ModelFormField:
            for error, lines in errors.iteritems():
                description = "\n".join(lines)
                flash(u"Error in the %s field - %s" % (
                    #getattr(form, field).label.text + " " + error,
                    form[field][error].label.text,
                    description
                ))
        else:
            for error, lines in errors.iteritems():
                description = "\n".join(lines)
                flash(u"Error in the %s field - %s" % (
                    #getattr(form, field).label.text + " " + error,
                    form[field].label.text,
                    description
                ))

Jinja side:

  {% with messages = get_flashed_messages(with_categories=true) %}
    {% for message in messages %}
      {% if "Error" not in message[1]: %}
        <div class="alert alert-info">
          <strong>Success! </strong> {{ message[1] }}
        </div>
      {% endif %}

      {% if "Error" in message[1]: %}
        <div class="alert alert-warning">
         {{ message[1] }}
        </div>
      {% endif %}
    {% endfor %}
  {% endwith %}

Hope that helps.

Barrybarrymore answered 6/9, 2018 at 20:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.