Table of contents
1.
Introduction
2.
WTForms
3.
Validating WTForms
4.
WTForms submission 
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024

Flask WTForms

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Flask is a web application framework written in Python. It is a microframework because it does not need specific tools or libraries to develop the applications. It supports extensions for object-relational mappers, form validation, upload handling, several standard framework-related tools, etc. WTForms is also a built-in module supported by Flask to provide an interactive user interface for an application. Let’s discuss WTForms and how to handle them in this article.

WTForms

Usually, the HTML forms we use are created with a <form> tag to design an interface. The data entered by a user is submitted in the form of an HTTP request message to the server-side script by either the GET or POST method. So because of this, the form elements have to be defined twice, once in HTML and again in the server-side script, and the form elements are challenging to render dynamically. So to overcome these limitations, we use WTForms.

The WTForms is a built-in module provided by Flask to provide an interactive user interface for an application. It is a flexible, form-rendering, and validating library. These forms provide a simple interface, allow us to define form fields in Python script, and render the form elements dynamically using HTML templates. WTForms also support validation for the elements. To use WTForms, we need to install it first.

pip install flask-WTF


The above command installs the Flask-WTF extension and all libraries, modules necessary in your machine. The installed package contains the Form class, a parent class for all the user-defined forms. Let us discuss few standard form fields among them.

Form Field Description
Text Field

Represents the text field

<input type=”text”> </input>

Boolean Field

Represents checkbox field

<input type=”checkbox”> </input>

Decimal Field Textfield used to display decimal numbers
Integer Field

Textfield used to display integers

<input type=”number”> </input>

Radio Field

Represents radio button field

<input type=”radio”> </input>

Select Field

Represents select form field

<select></select>

TextArea Field

Represents text area field

<textarea></textarea>

Password Field

Represents password input field

<input type=”password”> </input>

Submit Field

Represents submit form element

<input type=”submit”> </input>

Let’s explore how to write the code for WTForms.

from flask_wtf import Form  
from wtforms import TextField,SubmitField
from wtforms import validators, ValidationError  
  
class ContactForm(Form):  
   name = TextField("Candidate Name ",[validators.Required("Please enter your name.")])     
   email = TextField("Email",[validators.Required("Please enter your email address."),  
   validators.Email("Please enter your email address.")])    
  
   submit = SubmitField("Submit")
You can also try this code with Online Python Compiler
Run Code


We first created a WTForm in the above code by importing forms and required fields. Then, by using the fields we imported, we added name and email fields to the form to get the user's information. These inputs are taken using Textfield and SubmitField. We called the validator to validate the email given by the user.

Validating WTForms

from flask import Flask, render_template, request, flash  
from forms import ContactForm  
app = Flask(__name__)  
app.secret_key = 'development key'  
  
@app.route('/contact', methods = ['GET', 'POST'])  
def contact():  
   form = ContactForm()  
   if form.validate() == False:  
      flash('All fields are required.')  
   return render_template('contact.html', formform = form)  
  
@app.route('/success',methods = ['GET','POST'])  
def success():  
   return render_template("success.html")  
  
if __name__ == '__main__':  
   app.run(debug = True) 
You can also try this code with Online Python Compiler
Run Code


Whenever a form is created, it is important to validate it. We need to specify the required and nonrequired fields. The form.validate() function is used for validation of form. In the above code, if the data entered by the user is valid, it displays us a successful page; otherwise, it displays the error message.

Now let’s write the code for the HTML file.

<!doctype html>  
<html>  
   <body>  
      <h2 style = "text-align: center;">Registration Form</h2>  
          
      {% for message in form.name.errors %}  
         <div>{{ message }}</div>  
      {% endfor %}  
        
      {% for message in form.email.errors %}  
         <div>{{ message }}</div>  
      {% endfor %}  
        
      <form action = "http://localhost:5000/success" method = "POST">  
            {{ form.hidden_tag() }}  
            <div style = "font-size:18px;" font-weight:bold; margin-left:150px;>  
               {{ form.name.label }}<br>  
               {{ form.name }}  
               <br>   
               {{ form.email.label }}<br>  
               {{ form.email }}   
               <br><br>  
               {{ form.submit }}  
            </div>  
         </fieldset>  
      </form>  
   </body>  
</html> 


We are creating a basic HTML page for user interaction in the above code. We added error messages that everyone can understand for a more user-friendly nature. Then we are embedding all the fields in the form to display on the front end page. After the user gives input, the data gets submitted in the form of an HTTP request message, and the validation is done. If the data in all the given fields are valid, it shows us a successful message; otherwise, it displays an error message wherever necessary.

WTForms submission 

<!DOCTYPE html>  
<html>  
<head>  
    <title></title>  
</head>  
<body>  
<h1>Form posted successfully</h1>  
</body>  
</html>


The above code is to display the submission message. If the data is valid and an HTTP request is sent, the user gets a message “Form posted successfully”. This message is displayed for user confirmation.

FAQs

1. What is Flask-WTF used for?

Flask-WTF is an extension in Python used to build lightweight web applications with a simple user interface. It provides WTForms, which handle the forms better with validation and flexibility.

 

2. How do I import WTForms into a Flask?

We need to install the Flask-WTF extension to import it into our code. After installing, we can import it by using the following import statement.

from flask_wtf import Form 


3. How do I validate a Flask form?

We can validate the Flask form by calling the validators for the specific fields in the WTForms file and then by calling a .validate() function in the validation file to pass the data if it’s valid or displays an error message if it’s invalid. 

Key Takeaways

We have discussed WTForms, handling WTForms, validation, and submission in this article with detailed code.

Isn’t Flask interesting? If you find it interesting, go through the course we suggest and become an expert in writing flask codes.

Happy Learning!

Live masterclass