Creating Forms using Flask-WTF and WTForms
In this lesson, we will learn how to create forms using the Flask-WTF and WTForms modules.
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 toFlask
.
Introduction to
Flask-WTF
Flask-WTF
is aFlask
specific library that integrates theWTForm
library withFlask
. It acts as an add-on toWTForms
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:
- An input field for the email.
- An input field for the password.
- The submit button field.
For each possible field, wtforms
has associated classes. For this particular example we will only import the fields we need:
StringField
for an emailPasswordField
for a passwordSubmitField
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.