Creating Forms using Flask-WTF and WTForms

In larger applications, extra components such as the validation logic for email and password fields can easily become boiler-plate and hard to read. For this purpose, some libraries are used that can process them better.

Introduction to WTForms

WTForms is a library that makes form handling easy. It handles not only form validation but also form rendering at the front-end. Additionally, WTForms is not just limited to Flask.

Introduction to Flask-WTF

Flask-WTF is a Flask specific library that integrates the WTForm library with Flask. It acts as an add-on to WTForms and adds some extra components, such as security.

In this lesson, we will be using Flask-WTF in conjunction with WTForms to handle forms. Let’s get started.

How do we create the forms module?

To get started with Flask-WTF, we will first separate our application module from the forms module. Let’s add a new file called forms.py, which will act as the forms module.

Import FlaskForm from flask_wtf

First, we will import the FlaskForm class from the flask_wtf module. This class is a subclass of Form from the wtforms library.

from flask_wtf import FlaskForm

Create LoginForm class

For each form on our website, we will create a class. As we are making a login form. Therefore, let’s name this class LoginForm. This class will inherit from the FlaskForm class that we imported previously.

class LoginForm(FlaskForm):
    ...

Add form fields from wtforms

Our login form has three components:

  1. An input field for the email.
  2. An input field for the password.
  3. The submit button field.

For each possible field, wtforms has associated classes. For this particular example we will only import the fields we need:

  1. StringField for an email
  2. PasswordField for a password
  3. SubmitField for the submit button

Let’s import these classes.

from wtforms import StringField, PasswordField, SubmitField

Now we will make instances of these classes as member variables of our class, and we will pass the labels of these fields as input to the constructors.

Get hands-on with 1400+ tech skills courses.