- Flask - FastCGI
- Flask - Deployment
- Flask - Sijax
- Flask - SQLAlchemy
- Flask - SQLite
- Flask - WTF
- Flask - Mail
- Flask - Extensions
- Flask - File Uploading
- Flask - Message Flashing
- Flask - Redirect & Errors
- Flask - Sessions
- Flask - Cookies
- Sending Form Data to Template
- Flask - Request Object
- Flask - Static Files
- Flask - Templates
- Flask - HTTP Methods
- Flask - URL Building
- Flask - Variable Rules
- Flask - Routing
- Flask - Application
- Flask - Environment
- Flask - Overview
- Flask - Home
Flask Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Flask – Sending Form Data to Template
We have already seen that the http method can be specified in URL rule. The Form data received by the triggered function can collect it in the form of a dictionary object and forward it to a template to render it on a corresponding web page.
In the following example, ‘/’ URL renders a web page (student.html) which has a form. The data filled in it is posted to the ‘/result’ URL which triggers the result() function.
The results() function collects form data present in request.form in a dictionary object and sends it for rendering to result.html.
The template dynamically renders an HTML table of form data.
Given below is the Python code of apppcation −
from flask import Flask, render_template, request app = Flask(__name__) @app.route( / ) def student(): return render_template( student.html ) @app.route( /result ,methods = [ POST , GET ]) def result(): if request.method == POST : result = request.form return render_template("result.html",result = result) if __name__ == __main__ : app.run(debug = True)
Given below is the HTML script of student.html.
<html> <body> <form action = "http://localhost:5000/result" method = "POST"> <p>Name <input type = "text" name = "Name" /></p> <p>Physics <input type = "text" name = "Physics" /></p> <p>Chemistry <input type = "text" name = "chemistry" /></p> <p>Maths <input type ="text" name = "Mathematics" /></p> <p><input type = "submit" value = "submit" /></p> </form> </body> </html>
Code of template (result.html) is given below −
<!doctype html> <html> <body> <table border = 1> {% for key, value in result.items() %} <tr> <th> {{ key }} </th> <td> {{ value }} </td> </tr> {% endfor %} </table> </body> </html>
Run the Python script and enter the URL http://localhost:5000/ in the browser.
When the Submit button is cpcked, form data is rendered on result.html in the form of HTML table.
Advertisements