English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Flask Form Handling

We have seen that we can specify the http method in the URL rules. The function receiving the form data of the URL mapping can collect it in the form of a dictionary object and forward it to the template to present it on the corresponding webpage.

In the following example, URL => / Displaying a webpage with a form ( student.html). The filled data will be submitted to the URL that triggers the result() function => /result.

The results() function collects form data existing in request.form of the dictionary object, and sends it to result.html and displays it.

The template dynamically presents the HTML table of form data.

The following is the Python application code -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
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)

Below is student.html code of the HTML script.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask Example</title>
 </head>
    <body>
       <form action="http://localhost:5000/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>Mathematics Fraction: <input type="text" name="Mathematics" /></p>
          <p><input type = "submit" value = "Submit" /></p>
       </form>
    </body>
 </html>

The template code (result.html) is given below -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask Example</title>
 </head>
    <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 in the browser => http://localhost:5000/ . The result is as shown below -

When clicking SubmitWhen the button is clicked, the form data is displayed in the form of an HTML table result.html As shown below in Chinese -