EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Flask Tutorial Flask wtforms
Secondary Sidebar
Flask Tutorial
  • Flask
    • Flask Version
    • Flask make_response
    • Flask WebSocket
    • Flask Session
    • Flask Environment Variables
    • Flask Cache
    • Flask Server
    • Flask jsonify
    • Flask logging
    • Flask redirect
    • Flask wtforms
    • Flask config
    • Flask Users
    • Flask upload file
    • Flask? get post data
    • Flask Template
    • Flask DB Migrate
    • Flask HTTPS
    • Flask bcrypt
    • Flask debug mode
    • Flask authentication
    • Flask Migrate
    • Flask URL Parameters
    • Flask API
    • Flask bootstrap
    • Flask POST request
    • Flask Extensions

Flask wtforms

Flask wtforms

Definition of Flask wtforms

Flask WTForms is defined as a plugin that enables and eases out the process of designing forms in Flask web applications. This library intends to provide an interactive interface for the users for developing such forms. During coding of form data that is submitted to the browser, the code quickly becomes very hard to read. This library is present within a Flask plugin which can be installed using the pip command. WTForms has been an undisputed winner in terms of handling forms for years and is still the most widely used, the reason being the ease of rendering and validation along with being flexible. But one thing to note is that the flask-WTF plugin has the WTForms plugin as a dependency and both are intended to be used together!

Syntax:

In cases of the web application interface is an important element for the user and in HTML <form> tag is the provision of designing an interface along with pairing with text input, radio buttons, select, etc. which is used as appropriate to complete the need of the application’s utility. In this section, we will go through the syntax that enables us to implement Flask WTForms. So without much further ado let’s look at the syntax for the same:

Installation of Flask WTForms
pip install flask-WTF
Instantiating the FlaskForm object from Flask WTForms:
from flask_wtf import FlaskForm
Importing fields from wtforms library ( In this syntax we will take an example of TextField ):
from wtforms import TextField
Importing validators for Form validation:
from wtforms.validators import ValidationError, DataRequired

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,452 ratings)

How does wtforms work in Flask?

Before we learn about Flask wtforms, it is mandatory for us to learn some key concepts from its parent class, wtforms, from where many of the utilities are inherited. There are 4 key concepts that are equally important for Flask wtforms and they are as below:

  • The core container of WTForms is Forms that represents itself as a collection of fields and are accessed through form dictionary-style or attribute style.
  • The heavy lifting in a web application is done by Fields. Here every field represents a data type that enables coercing form input to the datatype. As an example, IntegerField and StringField are representations of 2 different data types and are non-interchangeable. There are important properties like label, description, etc. which come in handy while developing the web application.
  • The widget instance is another element of the Field. The HTML representation is rendered by the widget and that is what Widget’s primary job is. Each field has the utility of having a Widget instance attached to it.
  • The final component being the validator that is used for specifying validation rules for Fields. In one of our examples, we will go through a form validation rule to explain the hands-on implementation of the same.

With the 4 components discussed above, which work in a serialized way with Form being the initiator of the WTForms now we will look into 2 important usages of WTForms that is widely used in Flask application building. The first one being creating Forms:

  • With the 4 components discussed above, one can easily create a form by integrating Flask-WTF with WTForms. In the latest version releases, the fields need to be exclusively imported from WTForms. With this, the form created is added to an HTML template so that it can be rendered on a webpage. Additionally, one can use a CSRF token, a hidden field, which also gets generated automatically. Once the form is added to the HTML template, we add the form in the view function so that it can easily be referred to when rendered.
  • The next important piece is the validation which is an integral part of WTForms as it saves any Flask application to be secured and not fall into the prey of Cross-Site Request Forgery attacks. A set of validators are passed to the WTForms so as to run it to ensure that the form is validated through the field constructor’s second argument. The input is verified against the set of arguments and the criterion of the arguments. If the criterion is met, it is moved to the next page and if not, leads to a ValidationError.

With the above genre where WTForms is generally used, we have got a fair idea of Flask WTF working along with what capabilities is inherited from wtforms modules.

Examples

In this section, we will look at all the uses of WTForms in a Flask application, as by now we have already looked at the syntax and the way of working of WTForms of Flask application. This will be a hands-on feel of the theoretical learning we did above.

Example #1

Installation of Flask WTForms

Syntax:

pip install flask-WTF

Output:

Flask wtforms 1

Example #2

Instantiating the FlaskForm object from Flask WTForms

Syntax:

from flask_wtf import FlaskForm
FlaskForm

Output:

Flask wtforms 2

Example #3

Build a small Flask application using WTForms and validators

Syntax:

Here we need to build 3 different codes and the HTML file needs to be in a templates folder. Also, we need to make sure that the Flask-WTF is installed. Also, both the codes need to be in the same folder as well.

Forms.py
from flask_wtf import FlaskForm
from wtforms import SubmitField, StringField, validators
class EduCBASignUp(FlaskForm):
nameField = StringField('Name', [validators.Length(min=1)])
emailField = StringField('E-mail', [validators.Length(min=6, max=35)])
newsletterField = SubmitField('Sign me up for EduCBA!')
wtForms.py
from flask import Flask, render_template
from forms import EduCBASignUp
appFlask = Flask(__name__)
appFlask.secret_key = 'TheEduCBAway'
@appFlask.route('/signUp')
def signUp():
form = EduCBASignUp()
return render_template('login.html', title='Sign In', form=form)
if __name__ == "__main__":
appFlask.run(debug=True)
login.html
{% extends "base.html" %}
{% block content %}
<h1>Sign In</h1>
<form action="" method="post" novalidate>
{{ form.hidden_tag() }}
<p>
{{ form.nameField.label }}<br>
{{ form.nameField(size=32) }}
</p>
<p>
{{ form.emailField.label }}<br>
{{ form.emailField(size=32) }}
</p>
<p>{{ form.newsletterField() }}</p>
</form>
{% endblock %}

Output:

Flask wtforms 3

Conclusion

In this article, we have got to know about the working of Flask WTForms and how it works with validators in place. We can route errors in the validation rules so as to showcase custom messages if the inputs don’t follow the validation rules. Now it is in the hands of readers to apply the rules while building the Flask application!

Recommended Articles

This is a guide to Flask wtforms. Here we discuss the definition, How does wtforms work in Flask? and examples with code implementation. You may also have a look at the following articles to learn more –

  1. Flask Environment Variables
  2. Flask URL Parameters
  3. Flask HTTPS
  4. Flask DB Migrate
Popular Course in this category
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)
  41 Online Courses |  13 Hands-on Projects |  322+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more