English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Flask WTF

An important aspect of web applications is to provide users with a user interface. HTML provides a <form> tag for designing an interface. Appropriate use of form elements such as text input, radio buttons, and selections can be made.

User input data is submitted to the server-side script in the form of an HTTP request message via GET or POST methods.

The server-side script must recreate form elements by re-fetching data from http requests. Therefore, form elements must be defined twice in reality. - Once in HTML, and once in the server-side script. Another disadvantage of using HTML forms is that it is difficult (if not impossible) to dynamically present form elements. HTML itself cannot validate user input.

This is WTForms, where it is convenient to have a flexible form, rendering, and validation library. Flask-The WTF extension provides a simple interface for this WTForms library.

Using Flask-WTF allows form fields to be defined in Python scripts and presented using HTML templates. Validation can also be applied to WTF fields.

Let's take a look at how this dynamically generated HTML works.

Firstly, Flask needs to be installed-WTF extension.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
pip install flask-WTF

The installed software package includes a Form class, which must be used as the parent class for user-defined forms. The WTforms package includes definitions for various form fields. The following lists some standard form fields.

NumberStandard form fieldDescription
1TextFieldRepresents the <input type='text'> HTML form element
2BooleanFieldRepresents the <input type='checkbox'> HTML form element
3DecimalFieldUsed to display numbers as decimals
4IntegerFieldUsed to display integer text fields
5RadioFieldRepresents the <input type='radio'> HTML form element
6SelectFieldRepresents the selection form element
7TextAreaFieldRepresents the <textarea> HTML form element
8PasswordFieldRepresents the <input type='password'> HTML form element
9SubmitFieldRepresents the <input type='submit'> form element

For example, a form containing a text field can be designed as follows -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
from flask_wtf import Form
 from wtforms import TextField
 class ContactForm(Form):
     name = TextField("Name Of Student")

In addition to the name field, a hidden field for the CSRF token will also be automatically created. This is to prevent cross-site request forgery attacks.

When rendered, this will produce an equivalent HTML script as shown below.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
<input id="csrf_token" name="csrf_token" type="hidden"> />
 <label for="name">Name Of Student</label><br>
 <input id="name" name="name" type="text" value=""> />

User-defined form classes are used in Flask applications, and forms are presented using templates.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
from flask import Flask, render_template
 from forms import ContactForm
 app = Flask(__name__)
 app.secret_key = 'development key'
 @app.route('/contact')
 def contact():
     form = ContactForm()
     return render_template('contact.html', form = form)
 if __name__ == '__main__':
     app.run(debug = True)

The WTForms package also includes validator classes, which are very useful when validating form fields. The following list shows commonly used validators.

NumberValidator classDescription
1DataRequiredCheck if the input field is empty
2EmailCheck if the text in the field follows the email ID convention
3IPAddressVerify the IP address in the input field
4LengthVerify if the length of the string in the input field is within the given range
5NumberRangeValidate a number in the given input field range
6URLValidate the URL entered in the input field

Apply the 'DataRequired' validation rule to the name field of the contact form.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
name = TextField("Name Of Student", [validators.Required("Please enter your name.")])

The validate() function of the form object validates the form data and throws a validation error when the validation fails. The error message is sent to the template. Error messages are dynamically presented in the HTML template.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
{% for message in form.name.errors %}
    {{ message }}
 {% endfor %}

The following example demonstrates the concepts given above. The contact form code is as follows ( forms.py)。

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
from flask_wtf import Form
 from wtforms import TextField, IntegerField, TextAreaField, SubmitField, RadioField, SelectField
 from wtforms import validators, ValidationError
 class ContactForm(Form):
     name = TextField("Student Name", [validators.Required("Please enter your name.")])
     Gender = RadioField('Gender', choices = [('M', 'Male'), ('F', 'Female')])
     Address = TextAreaField("Address")
     email = TextField("Email", [validators.Required("Please enter your email address.")]),
       validators.Email("Please enter your email address.")])
     Age = IntegerField("Age")
     language = SelectField('Language', choices = [('cpp', 'C'))++'), ('py', 'Python')])
     submit = SubmitField("Submit")

The validator is applied to the name and email fields. Below is the Flask application script ( formexample.py)。

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
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 request.method == 'POST':
        if form.validate() == False:
           flash('All fields are required.')
           return render_template('contact.html', form = form)
        else:
           return render_template('success.html')
     elif request.method == 'GET':
           return render_template('contact.html', form = form)
 if __name__ == '__main__':
     app.run(debug = True)

template script ( contact.html) as shown below -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask Example</title>
 </head>
    <body>
      <h2 style = "text-align: center;">Contact 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/contact" method = "post">
          <fieldset>
             <legend>Items to fill in</legend>
             {{ form.hidden_tag() }}
             <div style = font-size:20px; font-weight:bold; margin-left:150px;>
                {{ form.name.label }}<br>
                {{ form.name }}
                <br>
                {{ form.Gender.label }} {{ form.Gender }}
                {{ form.Address.label }}<br>
                {{ form.Address }}
                <br>
                {{ form.email.label }}<br>
                {{ form.email }}
                <br>
                {{ form.Age.label }}<br>
                {{ form.Age }}
                <br>
                {{ form.language.label }}<br>
                {{ form.language }}
                <br>
                {{ form.submit }}
             </div>
          </fieldset>
       </form>
    </body>
 </html>

Run in Python shell formexample.py, and access the URL => http://localhost:5000/contact. The contact form will be displayed as follows.

If there is error information, the page will be as follows -

If there are no errors, it will display success.htmlThe content of the page, as shown below -