Sending Form Data to Template – FLASK

In previous sections, we saw how the HTTP method can be specified in the URL role. The Form data that is received by the triggered function, can collect it in form of the dictionary object, and forward the same to a template to render it on the webpage.

In the following example, the ‘/’ URL renders a web page (student.html) that 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 the 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 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>

Given below is the Python code of application

     
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)

The above code will produce a table with data entered in the form by user.