Form Validation with WTForms

    When you are working with WTForms you have to define your forms as classes first. I recommend breaking up the application into multiple modules (Large Applications as Packages) for that and adding a separate module for the forms.

    Getting the most out of WTForms with an Extension

    The extension expands on this pattern and adds a few little helpers that make working with forms and Flask more fun. You can get it from PyPI.

    This is an example form for a typical registration page:

    Notice we’re implying that the view is using SQLAlchemy here (), but that’s not a requirement, of course. Adapt the code as necessary.

    Things to remember:

    1. to validate the data, call the method, which will return True if the data validates, False otherwise.

    Now to the template side. When you pass the form to the templates, you can easily render them there. Look at the following example template to see how easy this is. WTForms does half the form generation for us already. To make it even nicer, we can write a macro that renders a field with label and a list of errors if there are any.

    Here’s an example _formhelpers.html template with such a macro:

    This macro accepts a couple of keyword arguments that are forwarded to WTForm’s field function, which renders the field for us. The keyword arguments will be inserted as HTML attributes. So, for example, you can call to add a class to the input element. Note that WTForms returns standard Python strings, so we have to tell Jinja2 that this data is already HTML-escaped with the |safe filter.

    Here is the register.html template for the function we used above, which takes advantage of the _formhelpers.html template: