Sending Form Data to Template
Flask – Sending Form Data to Template
Section titled “Flask – Sending Form Data to Template”A common pattern in web applications is to receive data submitted via an HTML form and then display that data back to the user, often on a confirmation or results page. Flask makes this straightforward using the request object and template rendering.
When an HTML form is submitted (typically using the POST method), the data entered by the user is sent in the body of the HTTP request. Flask provides access to this data through the request.form attribute. request.form behaves like a dictionary, mapping field names (from the name attributes of your form elements) to their submitted values.
You can collect this data in your view function and pass it to a template for rendering.
Consider this scenario: We have a page (/) that displays a form for entering student details (student.html). When the user submits the form, the data is sent via POST to another URL (/result). The view function handling /result will extract the form data and pass it to a template (result.html) which displays the submitted information in a table.
Here’s the Python code for the Flask application (app.py):
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')def student(): # Renders the initial form page return render_template('student.html')
@app.route('/result', methods=['POST', 'GET']) # Allow both POST (for submission) and GET (optional, for direct access)def result(): # Check if the request method is POST (i.e., form submitted) if request.method == 'POST': # Get the form data as an immutable dictionary result_data = request.form # Pass the dictionary to the result template return render_template("result.html", result=result_data) else: # Handle GET request (e.g., redirect or show an error/different page) # For simplicity, let's just return the student form again return redirect(url_for('student'))
if __name__ == '__main__': # Enable debug mode for development (auto-reloading, debugger) app.run(debug=True)The HTML for the form (templates/student.html):
<!doctype html><html><head> <title>Student Details</title></head><body> <h2>Enter Student Information</h2> <form action="{{ url_for('result') }}" method="POST"> <p>Name <input type="text" name="Name" /></p> <p>Physics Score <input type="text" name="Physics" /></p> <p>Chemistry Score <input type="text" name="Chemistry" /></p> <p>Maths Score <input type="text" name="Mathematics" /></p> <p><input type="submit" value="Submit" /></p> </form></body></html>Note: We use url_for('result') in the action attribute. This is the recommended way to generate URLs in Flask, as it’s more flexible than hardcoding paths.
The HTML for the results page (templates/result.html):
<!doctype html><html><head> <title>Submission Result</title></head><body> <h2>Submitted Information</h2> <table border="1"> <thead> <tr> <th>Field</th> <th>Value</th> </tr> </thead> <tbody> {# Loop through the key-value pairs in the 'result' dictionary #} {# Use .items() for Python 3 compatibility #} {% for key, value in result.items() %} <tr> <th>{{ key }}</th> <td>{{ value }}</td> </tr> {% endfor %} </tbody> </table> <br> <a href="{{ url_for('student') }}">Enter new data</a></body></html>In the result.html template, we iterate through the result dictionary (passed from the result() view function) using result.items(). For each key-value pair (representing a form field name and its submitted value), we create a table row.
To run this: Save the Python code as app.py, and the HTML files as templates/student.html and templates/result.html. Run python app.py and navigate to http://localhost:5000/ in your browser.
You will see the student information form. Fill it out and click ‘Submit’. The browser will make a POST request to /result, the result() function will process the request.form data, and render the result.html template, displaying the data you entered in a table.
While this example directly uses request.form, for more complex applications involving validation, data cleaning, and CSRF protection, using an extension like Flask-WTF (covered in another section) is highly recommended.