How To Use Web Forms in a Flask Application
Last Updated :
26 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
Profile Application using Python Flask and MySQL
A framework is a code library that makes a developer's life easier when building web applications by providing reusable code for common operations. There are a number of frameworks for Python, including Flask, Tornado, Pyramid, and Django. Flask is a lightweight web application framework. It is clas
10 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
Flask NEWS Application Using Newsapi
In this article, we will create a News Web Application using Flask and NewsAPI. The web page will display top headlines and a search bar where the user can enter a query, after processing the query, the webpage will display all relevant articles (up to a max of 100 headlines). We will create a simpl
7 min read
How To Integrate Ajax with Django Applications
Django is one of the most popular web frameworks for building robust and scalable web applications. However, many modern applications require asynchronous features, enabling real-time interactions without the need to reload the entire page. This is where Ajax (Asynchronous JavaScript and XML) comes
5 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
How to return a JSON response from a Flask API ?
Flask is one of the most widely used python micro-frameworks to design a REST API. In this article, we are going to learn how to create a simple REST API that returns a simple JSON object, with the help of a flask. Prerequisites: Introduction to REST API What is a REST API? REST stands for Represent
3 min read