Flask – Sending Form Data to Template

We have just already that the http technique can be determined in URL rule. The Form data gotten by the activated function can collect it as a word reference object and forward it to a layout to render it on a comparing web page.

In the accompanying model, '/' URL renders a site page (student.html) which has a structure. The data filled in it is presented on the '/result' URL which triggers the result() function.

The results() function collects structure data present in request.form in a dictionary object and sends it for rendering to result.html.

The format dynamically renders a HTML table of form data.

Given below is the Python code of use −

from flask import Flask, render_template, request
app = Flask(__name__)

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.

      <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>

Code of template (result.html) is given below −

<!doctype html>
      <table border = 1>
         {% for key, value in result.items() %}
               <th> {{ key }} </th>
               <td> {{ value }} </td>
         {% endfor %}
Run the Python script and enter the URL http://localhost:5000/ in the browser.

Submit Marks

When the Submit button is clicked, form data is rendered on result.html in the form of HTML table.