- Published on
Python Flask Forms with Jinja Templating
- Authors
- Name
- Ruan Bekker
- @ruanbekker
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
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
:
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
:
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:
├── app.py
└── templates
├── base.html
├── form.html
└── result.html
1 directory, 4 files
Then run the server:
python app.py
Screenshots
It should look like the following when you access http://localhost:5000/
After entering your form data, select "Submit", then you should see the following:
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, feel free to check out my website, and subscribe to my newsletter or follow me at @ruanbekker on Twitter.
- Linktree: https://go.ruan.dev/links
- Patreon: https://go.ruan.dev/patreon