How to get form data in Flask

In Flask, we can use the request object to get form data submitted in an HTTP POST request. The request object is part of the flask package and provides access to information about incoming requests. We can import this module using the following command:

from flask import request

The code example given below has the following file structure:

  • templates/form.html: This markup file contains a form. This file will be used to submit data to the application.

  • templates/success.html: This markup file will get the data from the application and render the data.

  • /app/App.py: This file contains the core logic of the Flask application. This file will use the data from the form.

Example

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('form.html')

@app.route('/submit-form', methods=['POST'])
def submit_form():
    name = request.form.get('name')
    email = request.form.get('email')
    message = request.form.get('message')
    print(f"Name: {name}, Email: {email}, Message: {message}")
    return render_template('success.html', name=name)

if __name__ == '__main__':
    app.run(debug=True)
Getting form data in Flask

Explanation

The example code works as follows:

  • Line 9: The submit_form() method as a decoration of method=['POST'] defines that this method will only accept the POST requests.

  • Line 11-13: In this method, we use request.form.get() to get the data from the form. The request is a library from flask and request.form contains a dictionary containing all the values submitted using the form. This dictionary has the following structure:

  • Line 14-15: Names of form fields as the keys of the dictionary. Submitted values as the values against keys in the dictionary

  • Line 15: Finally, we use the render_template() function to render a template. This is also available in the flask package. This function is used to generate HTML files. This method accepts the file name to render and another optional parameter for data that can be accessed using the Jinja2 syntax ({{name}}) in the HTML files.

Note: To learn about Flask, see this Answer.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved