HTML forms are an integral part of modern web development. They allow users to enter data that can be processed by web servers.
However, it can often be a tedious task for developers to create forms that are user-friendly and provide real-time rendering capabilities. This is where Flask WT Forms comes in.
Flask WT Forms is a module that enables developers to build HTML forms in a straightforward and efficient manner. In this article, we will explore the need for Flask WT Forms and how to build a Flask WT Form.
We will also cover the installation process and provide an overview of the syntax, field types, and validators.
The Need for Flask WT Forms
Creating HTML forms can be a time-consuming process, leaving developers looking for ways to streamline the process. Flask WT Forms provides a solution to this problem by enabling developers to create forms in almost no time.
One of the benefits of Flask WT Forms is the ability to validate user input. Validation can help reduce the amount of bad data entering the system, improving data quality and accuracy.
Flask WT Forms allow for validation to be completed either on the client side with JavaScript or on the server side with Python. This means that users receive instant feedback, which is a great user experience.
Building a Flask WT Form
Before we can start building a Flask WT Form, we need to install the module.
Installing WT Forms into your System
There are two main methods to install Flask WT forms, and we will explore them below. Method One: Installing Flask-WTF via pip package manager
Flask-WTF is a Python package that allows us to create forms with Flask.
Before using Flask-WTF, we need to install it.
Here are the steps to install Flask-WTF via pip package manager:
- Open your terminal or command prompt.
- Enter the following command to install Flask-WTF:
pip install Flask-WTF
Method Two: Installing Flask-WTF via the requirements.txt file
The requirements.txt file is a file where all of your project’s dependencies are listed. By adding Flask-WTF to this file, you can install it in one command that will install all the dependencies.
Here are the steps to install Flask-WTF via requirements.txt file:
- Open your terminal or command prompt.
- Navigate to your project directory.
- Open the requirements.txt file.
- Add the following line:
Flask-WTF
- Save and close the file.
- In your terminal or command prompt, enter the following command:
pip install -r requirements.txt
Once you have installed Flask-WTF, it’s time to start building your form.
Building a Flask WT Form
To build a Flask WT Form, you need to create a new file called forms.py. This file should contain the form class and its fields.
Here is an example of a form that collects the user’s first name, last name, and email:
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, Email
class ContactForm(FlaskForm):
first_name = StringField('First Name', validators=[DataRequired()])
last_name = StringField('Last Name', validators=[DataRequired()])
email = StringField('Email',validators=[DataRequired(),Email()])
submit = SubmitField('Send')
The above code defines a new form called ContactForm. The form has three fields: first_name, last_name, and email.
Each field is defined with the StringField class from the wtforms module. StringField takes the field label as its first argument and any validators as its second argument.
In the above code, we have applied the DataRequired and Email validators to the email field. DataRequired is used to ensure that the user has entered some data, whereas Email is used to validate the email address entered.
We have also included a submit button in the ContactForm that is defined by the SubmitField class and has a label “Send.”
Summary
In this article, we explored the need for Flask WT forms and how to install and build a form using the Flask WT Forms module. We also looked at some examples of field types and validators that can be used to validate user input in the form.
Flask WT Forms offers many benefits, including real-time rendering of data, validation of user input to prevent bad data entering the system, and a streamlined form creation process. With Flask WT Forms, web developers can create user-friendly HTML forms in a straightforward and efficient manner.
Coding a Simple WT Form in Forms.py file
Now that we have installed Flask-WTF and have an understanding of why we need it, it’s time to build a simple WT Form. In this section, we will look at the syntax and field types used in Flask WT Forms.
WT Form Syntax
Below is the syntax for a simple Flask WT Form:
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
class SimpleForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
submit = SubmitField('Submit')
In the above code, we have a form that has a single text field (name) and a submit button. We can specify any number of fields in our form by using the appropriate class from the wtforms module.
WT Form Field Types
WT Forms provide a variety of field types that developers can use to design their forms. Here is a list of some common field types that are supported by Flask-WTF:
- StringField: This field allows the user to enter any type of text as input.
- IntegerField: This field allows the user to enter only integers.
- DecimalField: This field allows the user to enter floating-point values.
- BooleanField: This field is used when we need a checkbox in the form.
- DateField: This field is used when we need to collect date input from the user.
- SelectField: This field allows the user to choose from a dropdown menu.
- TextAreaField: This field is used when we need to collect multi-line text input from the user.
- PasswordField: This field is used to collect passwords and hides the actual entered data.
Example of Student Form code
Let’s take an example of a Student Form and see how we can use the above field types in the form.
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, IntegerField, DecimalField, DateField, SelectField, TextAreaField
from wtforms.validators import DataRequired, Length
class StudentForm(FlaskForm):
first_name = StringField('First Name', validators=[DataRequired(), Length(min=2, max=50)])
last_name = StringField('Last Name', validators=[DataRequired(), Length(min=2, max=50)])
age = IntegerField('Age', validators=[DataRequired()])
gpa = DecimalField('GPA', validators=[DataRequired()])
date_of_birth = DateField('Date of Birth (YYYY-MM-DD format)', validators=[DataRequired()], format='%Y-%m-%d')
major = SelectField('Major', choices=[('Computer Science', 'Computer Science'),('Biology', 'Biology'), ('Mathematics', 'Mathematics')], validators=[DataRequired()])
address = TextAreaField('Address', validators=[DataRequired(), Length(min=5)])
submit = SubmitField('Submit')
In this Student Form, we have used different field types such as StringField, IntegerField, DecimalField, DateField, SelectField, and TextAreaField. We have also applied validation to these fields using different validators from the wtforms.validators module.
The Student Form collects the student’s first name, last name, age, GPA, date of birth, major, and address.
Coding the main Flask file
So far, we have created a form and defined its fields in forms.py. Now, we need to connect this form with our Flask application by creating a main Flask file that displays the form and processes the data.
Flask View for displaying the form and processing the data
Here is an example of how we can create a Flask View for the Student Form:
from flask import Flask, render_template, request
from forms import StudentForm
app = Flask(__name__)
app.config['SECRET_KEY'] = 'some_secret_key'
@app.route('/', methods=['GET', 'POST'])
def index():
form = StudentForm()
if form.validate_on_submit():
first_name = form.first_name.data
last_name = form.last_name.data
age = form.age.data
gpa = form.gpa.data
date_of_birth = form.date_of_birth.data
major = form.major.data
address = form.address.data
return f"Hello, {first_name} {last_name}. You are {age} years old and have a {gpa} GPA. Your birth date is {date_of_birth}, and your major is {major}. Your address is {address}."
return render_template('index.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
In the above code, we have created a Flask View that displays the student form on the web page.
We have imported the StudentForm from forms.py and used it to create an instance of the form.
The form.validate_on_submit() function is used to check whether the form is successfully submitted or not.
If the form is submitted, we are fetching the field data entered by the user and displaying them on the web page. The index.html file is the main HTML file that renders the form.
We will create this file shortly.
Processing Data
When the user submits the form, the data is sent to the server’s POST request. The Flask View that is responsible for the form processing listens to these requests and uses the data to process the form.
In this example, we are using the form data to display on the web page. However, we can also use the form data to update a database or perform other operations.
Summary
In this article, we have discussed how to code a simple Flask WT Form, syntax, and field types. We have written an example of a Student Form and explained how to validate the data entered by the user.
We then created a Flask View that displays the form and processes the data entered by the user.
Flask WT Forms provide a streamlined and efficient way to create HTML forms with ease.
By using the appropriate field types and validators, developers can ensure that the form data is accurate and reliable. Flask-Wt Forms also provide real-time rendering of data, which improves the user experience.
With Flask-WTF, developers have a powerful tool for creating forms that require minimal coding and validation efforts.
Creating the Templates for the Form
Now that we have built the Student Form and our Flask application, we need a template to render the form on the web page. In this section, we will look at how to include the WT Form in an HTML template and provide an example of a Student Form HTML template.
Including the WT Form in HTML template
To add a form to an HTML template, we need to link the form fields to the HTML page. The most common way to do this is by extending the base HTML template.
Here is an example:
{% extends "base.html" %}
{% block content %}
{% endblock %}
In the above HTML code, we have linked the form fields to the HTML page using the Flask-WTF syntax. We have also used div tags to enclose each form field.
The form fields are printed on the web page using the WT Forms syntax.
Example of a Student Form HTML template
Here is an example of a Student Form HTML template that demonstrates how to include a WT Form in an HTML file: