Ruan Bekker's Blog

From a Curious mind to Posts on Github

Python Flask Forms With Jinja Templating

ruanbekker-blog

In this tutorial, we will demonstrate how to use Python Flask and render_template to use Jinja Templating with our Form. The example is just a ui that accepts a firstname, lastname and email address and when we submit the form data, it renders on a table.

Install Flask

Create a virtual environment and install python flask

1
2
3
python3 -m pip install virtualenv
python3 -m virtualenv -p python3 .venv
source .venv/bin/activate

The Code

First we will create our application code in app.py:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from flask import Flask, render_template, request

app_version = '1.1.0'

app = Flask(__name__)

@app.route('/')
def root():
    return render_template('form.html')

@app.route('/result',methods = ['POST', 'GET'])
def result():
    if request.method == 'POST':
        result = request.form
        json_result = dict(result)
        print(json_result)
        return render_template("result.html", result=result, app_version=app_version)

if __name__ == '__main__':
    app.run(debug = True)

As you can see our first route / will render the template in form.html. Our second route /result a couple of things are happening:

  • If we received a POST method, we will capture the form data
  • We are then casting it to a dictionary data type
  • Print the results out of our form data (for debugging)
  • Then we are passing the result object and the app_version variable to our template where it will be parsed.

When using render_template all html files resides under the templates directory, so let’s first create our base.html file that we will use as a starting point in templates/base.html:

1
mkdir templates

Then in your templates/base.html:

In our templates/form.html we have our form template, and you can see we are referencing our base.html in our template to include the first bit:

Then our last template templates/result.html is used when we click on submit, when the form data is displayed in our table:

So our directory structure should look like this:

1
2
3
4
5
6
7
├── app.py
└── templates
    ├── base.html
    ├── form.html
    └── result.html

1 directory, 4 files

Then run the server:

1
python app.py

Screenshots

It should look like the following when you access http://localhost:5000/

python-flask-forms

After entering your form data, select “Submit”, then you should see the following:

python-flask-forms

So you can see that our request data was parsed through the template and our app version variable as well.

Thank You

Thanks for reading, if you like my content, check out my website, read my newsletter or follow me at @ruanbekker on Twitter.

ruanbekker-cheatsheets