Flask sends form data to template Flask to send form data to the template we have seen that http method can be specified in the URL rule.Form data received by the trigger function can be collected in the form of a dictionary object and forwarded to the template to render it on the corresponding web page.

Related course: Python Flask: Create Web Apps with Flask

Example

Url routing

In the following example, the ‘ /‘ URL presents a web page with a form (student.html).The data populated is published to the ‘/result’ URL that triggered the result () function.

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

This template dynamically renders an HTML table of form data.

The Python code of the application is given below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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 template

Then create student.html

1
2
3
4
5
6
7
<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>

The template will look like this once you open the browser url:

the flask form (student.html)

Show data

And result.html

1
2
3
4
5
6
7
8
9
10
11
<!doctype html>
<table border = 1>
{% for key, value in result.items() %}

<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>

{% endfor %}
</table>

Run the Python script and enter the URL localhost:5000/ in the browser.

Then click submit, it will output the data in the template:

show flask template data (result.html)

Related course: Python Flask: Create Web Apps with Flask