Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WTForms getting the errors

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 
like image 778
Romeo M. Avatar asked Jun 24 '11 03:06

Romeo M.


People also ask

What is WTForms in Python?

WTForms is a Python library that provides flexible web form rendering. You can use it to render text fields, text areas, password fields, radio buttons, and others. WTForms also provides powerful data validation using different validators, which validate that the data the user submits meets certain criteria you define.

Should I use WTForms?

WTForms are really useful it does a lot of heavy lifting for you when it comes to data validation on top of the CSRF protection . Another useful thing is the use combined with Jinja2 where you need to write less code to render the form. Note: Jinja2 is one of the most used template engines for Python.

Is Flask WTF good?

Flask-WTForms is a great tool to help with form validation (e.g., avoidance of Cross-Site Request Forgery (CSRF)). Flask-WTForms can help create and use web forms with simple Python models, turning tedious and boring form validation into a breeze.


2 Answers

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 
like image 81
Sean Vieira Avatar answered Oct 01 '22 05:10

Sean Vieira


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 %} 
like image 34
Wolph Avatar answered Oct 01 '22 04:10

Wolph