Open In App

How To Use Web Forms in a Flask Application

Last Updated : 01 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. Create an HTML page that will contain our form.
  2. Create a Flask application that will act as a backend.
  3. Run the Flask application and fill out the form.
  4. Submit the form and view the results.

File Structure:

This is the File structure after we complete our project:

How to Get Form Data in Flask

 

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:

  1. 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.
  2. 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>
        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>
  
        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:

  1. One will be the default endpoint or home page. It will display our HTML UI template for the form.
  2. 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:

How to Get Form Data in Flask

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads