How To Use Python Flask-WTForms

Hello in this tutorial, we will see how to use Flask WTForms in Python, through a simple application.

1. Introduction

WTF in python is used to create an interactive form in the flask web applications and also serves as the validation library for the form. What is useful:

  • The form elements are sent with the request object from the client to the server-side
  • Server-side script recreates the form element as there is no mapping between the client HTML form elements and variables used at the server-side
  • WTF does not allow rendering HTML form data in real-time

1.1 WT form fields

The following table shows the standard form fields –

Form FieldDescription
TextFieldRepresent the text field HTML form element
BooleanFieldRepresent the checkbox HTML form element
DecimalFieldRepresent the text field to display the numbers with decimals
IntegerFieldRepresent the text field to display the integer values
RadioFieldRepresent the radio button HTML form element
SelectFieldRepresent the select form element
TextAreaFieldRepresent the text area HTML form element
PasswordFieldUsed to take the password as the form input from the user
SubmitFieldIt provides represents the <input type = ‘submit’ value = ‘Submit’> html form element

2. Setting up Python and important modules

To start with this tutorial we will need to install Python and set up some of the python libraries. Let us go ahead and install them one by one.

2.1 Setting up Python

If someone needs to go through the Python installation on Windows, please watch this link. You can download the Python from this link.

2.2 Setting up Flask libraries

Once the python is successfully installed on your system you can install the Flask and Flask-WTF modules using a simple pip command. You can fire the below command from the command prompt and it will successfully download the modules from and install it.

Installation command

pip install -U Flask Flask-WTF

3. How To Use Python Flask-WTForms

I am using JetBrains PyCharm as my preferred IDE. You’re free to choose the IDE of your choice.

3.1 Creating an implementation file

Add the following code to the python script. The file will contain the Flask app, routes, and form using the Flask WTF module. WT form will use the SECRET_KEY as a CSRF token to the application.

# python - wt forms tutorial

# modules
from os import urandom

from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, Length

app = Flask(__name__, template_folder='.')
app.config['SECRET_KEY'] = urandom(16)

# user form class
class WelcomeUserForm(FlaskForm):
    name = StringField(label='Enter name: ',
                           DataRequired(message='Name is required'),
                           Length(min=4, message='Name must be greater than %(min)d characters')
    submit = SubmitField(label='Submit')

# application endpoint to render the html file and perform post op
# endpoint -
@app.route('/', methods=['GET', 'POST'])
def welcome():
    form = WelcomeUserForm()
    if form.validate_on_submit():
        return f'''<h4>Hello {}</h4>'''

    return render_template('form.html', form=form)

# driver code
if __name__ == '__main__':

3.2 Creating an implementation file

Add the following code to the HTML file. We will use the form object to pass the WT form elements into the template parser for the Flask. The CSRF token protect the application against CSRF attacks.


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8"/>
    <link rel="stylesheet" href="">
<form method="POST" action="">
    <div class="form-row">
        <div class="form-group col-md-6">
            {{ form.csrf_token() }}
            <label class="control-label col-sm-2"> {{ }}</label>
            <div class="col-sm-10">
                {{ }}
            {% for field, errors in form.errors.items() %}
            <small class="form-text text-muted">
                {{ ', '.join(errors) }}
            {% endfor %}
        <div class="form-group">{{ form.submit(class="btn btn-primary") }}</div>

4. Run the application

Run this script and the application will be started on the port number – 5000. Once the application is started successfully open the browser of your choice and hit the localhost endpoint.

The index page will be shown to the user as shown in Fig. 1.

flask wtforms - index page
Fig. 1: Index page

Enter a name in the input field and the greeting message will be shown to the user as per the route defined in the script.

flask wtforms - welcome page
Fig. 2: Welcome page

The HTML form also consists of the validation such as required or max length for the name field and will be shown to the user if the form validation fails as shown in Fig. 3.

Fig. 3: Form validation

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

5. Summary

This was the tutorial to learn about the WT forms in python programming where we saw that the WT forms are responsible to create interactive forms in flask web applications and also support form validation. You are free to change the source code and can download it from the Downloads section.

6. Download the Project

This was a tutorial on how to use WT forms in python programming.

You can download the full source code of this example here: How To Use Python Flask-WTForms

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions



An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button