Updated April 19, 2023
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
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:
Example #2
Instantiating the FlaskForm object from Flask WTForms
Syntax:
from flask_wtf import FlaskForm
FlaskForm
Output:
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:
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 –