[Flask] Flask sends form data to the template

Flask sends form data to the template

We have seen that the http method can be specified in the URL rules. The Form  data received by the trigger function  can be collected in the form of a dictionary object and forwarded to the template to present it on the corresponding web page.

In the following example, the '/' URL  will render a web page with a form (student.html). The filled data will be published to the '/result' URL that triggers the  result()  function  .

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

This template dynamically renders an HTML table of form data.

Given below is the Python code of the 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)

Given below is the HTML script of  student.html  .

 <form action="http://localhost:5000/result&quot" 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>

The code for the template (result.html) is given below :

< > and other escape characters, please refer to https://blog.csdn.net/u013066730/article/details/108358895

It was found that the escape character was not good, so it was unnecessary.

<!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 clicked, the form data is presented on result.html  in the form of an HTML table  .

 

Guess you like

Origin blog.csdn.net/u013066730/article/details/108358373