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
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.
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.
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.
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
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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With