Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
wb_sunny

Flask WT Forms

Flask WTF

Welcome to this tutorial! Today we will look into a forms library in the Flask web framework known as Flask WT Forms.

The need for Flask WT Forms

Though the HTML forms are acceptable to use,  they have certain shortcomings:

  • There is no direct link between the client-side HTML form and the server-side Flask application. That is, the form data is sent along with the request object from the Client-side(User) to the server-side. And hence Flask View has to recreate the form elements back again to process them.
  • The HTML forms are challenging to render dynamically in real-time.
  • HTML forms do not provide a way to Validate user input.

Thus it is preferable to use Flask WT Forms in our application code.

Building a Flask WT Form

The best way to understand it is to try it ourselves. In this section we will do exactly that! So buckle up and lets get started.

1. Installing WT Forms into your System

To use WT Forms we must first install it. Here we are using PIP to install it. So in your terminal, run the command

pip install flask-wtf

That’s it now we are ready to use it.

2. Coding a Simple WT Form in Forms.py file

The WT forms should be present in a separate “forms.py” file. Hence create a new forms.py file beside your main Flask file.

File Location
File Location

Now the syntax for a WT form looks like this:

from flask_wtf import Form
from wtforms import Field1, Field2, Field3 ......, SubmitField

class FormName(Form):
   Fied1_name = Field1("Display_name")
   Fied2_name = Field2("Display_name")
   Fied3_name = Field3("Display_name")

   submit = SubmitField("Submit")

Here the fields inside the Form Class could be:

Form FieldDescription
TextFieldIt is analogous to the Input type – Text in HTML form attribute
BooleanFieldIt is analogous to the Input type – CheckBox in HTML form attribute
DecimalFieldIt is the TextField to display numbers with decimal places
IntegerFieldIt is the TextField to display Integer numbers
RadioFieldIt indicates the radio button HTML form element
SelectFieldIt indicates the Select form element
TextAreaFieldIt is analogous to the Input type -Text Area in HTML form attribute
PasswordFieldIt takes a password as form input from the users.
SubmitFieldIt is analogous to the Input type –Submit in HTML Form attribute
Form Fields

We can also add validators to our Form Fields. Now let us code a simple Student Form in our forms.py file:

from flask_wtf import Form
from wtforms import TextField, IntegerField, SubmitField
from wtforms import validators, ValidationError

class StudentForm(Form):
   name = TextField("Student Name", [validators.Required("Please enter your name")])
   marks = IntegerField("Marks", [validators.Required("Please enter your marks")])
   email = TextField("Email",[validators.Required("Please enter your email"),validators.Email("Invalid email address")])
   
   submit = SubmitField("Submit")

Here you might get an error if you don’t have email_validator installed in your device. To fix that, just install the email_validator :

pip install email_validator

That’s it it will work now.

3. Coding the main Flask file

Now we will include the Form in our main file. Consider the following code:

from flask import Flask,render_template, request
from forms import StudentForm

app = Flask(__name__)
app.secret_key = 'form_csrf_token_security_key'

@app.route('/form', methods = ['POST', 'GET'])
def FormView():
    form = StudentForm()

    if request.method =='POST':
        form = StudentForm()
        if form.validate()== True:
            return "Process Successful"
        return render_template('form.html', form = form)
    
    return render_template('form.html', form = form)
            

app.run(host='localhost', port=5000)

Here:

  • We call the Form as a Class object. When the user opens the site for the first time(GET method), the StudentForm() will be empty. Hence we will get an empty form.
  • When he submits the form (POST method), the StudentForm() class object now contains the user data. If the data is valid, it will return – “Process Successful.

This is the code logic that we are using here👆.

The secret key is needed to unlock the CSRF security token in the HTML form template.

4. Creating the Templates for the Form

Now, to display the form to the user, we must include it in the HTML template file. The syntax to include the WT Form in HTML is:

<form action = "http://localhost:5000/endpoint" method = post>
{{ form.hidden_tag() }}
         {{ form.field_name1.label }}<br>
         {{ form.field_name1 }}
         <br>

         {{ form.field_name2.label }}<br>
         {{ form.field_name2 }}
         <br>

         {{ form.field_name3.label }}<br>
         {{ form.field_name3 }}
         <br>

         {{ form.submit }}
</form>

Here,

  • {{ form.hidden_tag() }} is the hidden CSRF token field, which takes the security key mentioned in the main Flask application file.
  • {{ form.field.Label }} indicates the Field name.
  • {{ form.field }} indicates the Field input Box.

Hence the Template file “form.html” for our StudentForm will be:

<form action = "http://localhost:5000/form" method = post>
{{ form.hidden_tag()}}
         {{ form.name.label }}<br>
         {{ form.name }}
         <br>

         {{ form.marks.label }}<br>
         {{ form.marks }}
         <br>

         {{ form.email.label }}<br>
         {{ form.email }}
         <br>

         {{ form.submit }}
</form>

Do check out our Flask templates article to know more about Templates

5. Implementing the Flask Application

That’s it with the coding part!! Now lets fire up the server

python filename.py

Go to “/form

Flask WT Forms
WT Form

Enter the details and then hit submit.

Success Page
Success Page

Nice !!

Conclusion

That’s it, guys !! That was all about Flask WT forms. Do check out our Flask Forms article to know more about Flask HTML forms. To learn more about Flask WT Forms, read the documentation here.

We will see you guys in the next article. Till then, Happy Coding !!