How To Use Web Forms in a Flask Application
Last Updated :
28 Apr, 2025
A web framework called Flask provides modules for making straightforward web applications in Python. It was created using the WSGI tools and the Jinja2 template engine. An example of a micro-framework is Flask. Python web application development follows the WSGI standard, also referred to as web server gateway interface. It is recognized as the specification for the standard interface used by the server and web application. Jinja2 is a web template engine that combines a template with a particular data source to produce dynamic web pages.
Steps that we will follow to Use Web Forms in a Flask Application:
- Create an HTML page that will contain our form.
- Create a Flask application that will act as a backend.
- Run the Flask application and fill out the form.
- Submit the form and view the results.
File Structure:
This is the File structure after we complete our project:
Create an HTML page that will contain our form
To create an HTML page, we will use the most popular Bootstrap framework. It has pre-defined CSS and JS classes which will help us to create a good-looking form with minimal code. To create this HTML form one needs to know the basics of HTML. The two major points to look at in the below code are:
- The form action points to the URL that is defined by the read_form() definition in our Flask application. The endpoint is triggered on submitting the form by clicking on the Submit button. Please note that anything written within double curly braces {{...}} is interpreted as Python code. The form method is defined as POST since we will pass the form data in the body section of our request.
- For each form element, there is a 'name' attribute which we will use to point to the respective elements in our Flask application. So make sure, you keep them unique and readable. For example, the name attribute for the email and password fields are userEmail and userPassword respectively.
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Flask demo</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
</head>
<body>
<h1 class="text-center py-5">Flask Form Data Demo</h1>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<form action="{{ url_for('read_form')}}" method="post">
<label for="email" class="form-label">Email address</label>
<input name="userEmail" type="email" class="form-control" id="email">
<label for="password" class="form-label">Password</label>
<input name="userPassword" type="password" class="form-control" id="password">
<label for="exampleInputEmail1" class="form-label">Contact</label>
<input name="userContact" class="form-control" id="exampleInputEmail1">
<div class="form-check form-check-inline py-3">
<input class="form-check-input" type="radio" name="genderMale" id="male"
value="Male" checked>
<label class="form-check-label" for="male">Male</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="genderFemale" id="female"
value="Female">
<label class="form-check-label" for="female">Female</label>
</div>
<div class="form-check form-switch py-3">
<input class="form-check-input" type="checkbox" role="switch" id="switch" checked>
<label class="form-check-label" for="switch">Subscribe to Newsletter</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<div class="col-md-4"></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3"
crossorigin="anonymous"></script>
</body>
</html>
Create a Flask application that will act as a backend
The Flask application will read the data from our form whenever a request is made to the backend. In our Flask application, we will have 2 endpoints:
- One will be the default endpoint or home page. It will display our HTML UI template for the form.
- The other will extract the form data and display the result in raw format.
In the code, we can see that we are returning the index.html template for the root endpoint. We have another endpoint named read-form which reads the form using the Flask request method. The code request.form will return an ImmutableDict type object which contains the form data as key-value pairs just like Python dict objects. Once we load this data in a variable, we can use the variable as a dictionary to request any information regarding the key. We can notice that the key mentioned in the code to retrieve the form data is nothing but the ones we defined within the name attribute in our HTML code. We must use the exact same name as shown. The form data is then returned from the read-form endpoint as a dict type.
Python3
# Importing required functions
from flask import Flask, request, render_template
# Flask constructor
app = Flask(__name__)
# Root endpoint
@app.route('/', methods=['GET'])
def index():
## Display the HTML form template
return render_template('index.html')
# `read-form` endpoint
@app.route('/read-form', methods=['POST'])
def read_form():
# Get the form data as Python ImmutableDict datatype
data = request.form
## Return the extracted information
return {
'emailId' : data['userEmail'],
'phoneNumber' : data['userContact'],
'password' : data['userPassword'],
'gender' : 'Male' if data['genderMale'] else 'Female',
}
# Main Driver Function
if __name__ == '__main__':
# Run the application on the local development server
app.run()
Run the Flask application and fill out the form
We can run the flask application (assuming the filename to be app.py) using the python app.py command in the terminal.
$ python app.py
* Serving Flask app 'main'
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
Press CTRL+C to quit
Then go to the URL http://127.0.0.1:5000 and you should be able to see our HTML form.
Submit the Flasks Form and view the Data Entered
When finished, click the submit button. You should be able to view the following output after a successful answer. Please be aware that while I utilized a JSON beautifier plugin in my browser, the final product may not look exactly the same in your browser.
Output:
Similar Reads
How to Run a Flask Application After successfully creating a Flask app, we can run it on the development server using the Flask CLI or by running the Python script. Simply execute one of the following commands in the terminal:flask --app app_name runpython app_nameFile StructureHere, we are using the following folder and file.Dem
4 min read
How to Add Authentication to App with Flask-Login We can implement authentication, login/logout functionality in flask app using Flask-Login. In this article, we'll explore how to add authentication to a Flask app using Flask-Login.To get started, install Flask, Flask-Login, Flask-SQLAlchemy and Werkzeug using this command:pip install flask flask_s
6 min read
Using JWT for user authentication in Flask JWT (JSON Web Token) is a compact, secure, and self-contained token used for securely transmitting information between parties. It is often used for authentication and authorization in web applications. A JWT consists of three parts:Header - Contains metadata (e.g., algorithm used for signing).Paylo
6 min read
How to Get Data from API in Python Flask In modern web development, APIs (Application Programming Interfaces) play a crucial role in enabling the interaction between different software systems. Flask, a lightweight WSGI web application framework in Python, provides a simple and flexible way to create APIs. In this article, we'll explore ho
2 min read
How to write a simple Flask API for hello world? Prerequisites: Introduction to REST APIÂ REST stands for Representational State Transfer and is an architectural style used in modern web development. It defines a set of rules/constraints for a web application to send and receive data. In this article, we are going to learn how to create a simple R
3 min read
Setting Up Flask Applications in Google Cloud Run Flask is a popular and easy to use Python web framework that is lightweight and flexible. It lets programmers quickly and with minimal code construct web applications. Flask is simple to modify to match the requirements of different project types since it allows you to choose the tools and libraries
5 min read
Form Submission API with Swagger Editor and Python Flask Creating user-friendly APIs is essential for seamless interaction between applications. Leveraging tools like Swagger Editor alongside Python Flask, developers can streamline the process of designing, documenting, and implementing APIs. In this guide, we'll explore how to craft a Form Submission API
3 min read
How to Build a Web App using Flask and SQLite in Python Flask is a lightweight Python web framework with minimal dependencies. It lets you build applications using Python libraries as needed. In this article, we'll create a Flask app that takes user input through a form and displays it on another page using SQLite.Run the following commands to install Fl
3 min read
How to create a form using Django Forms ? This article explains how to create a basic form using various form fields and attributes. Creating a form in Django is very similar to creating a model, you define the fields you want and specify their types. For example, a registration form might need fields like First Name (CharField), Roll Numbe
2 min read
Create a Weather app using Flask | Python Prerequisite : Flask installation Flask is a lightweight framework written in Python. It is lightweight because it does not require particular tools or libraries and allow rapid web development. today we will create a weather app using flask as a web framework. this weather web app will provide curr
2 min read