WTForms getting the errors

Romeo M. picture Romeo M. · Jun 24, 2011 · Viewed 23.5k times · Source

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

Answer

Sean Vieira picture Sean Vieira · Jun 24, 2011

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