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 |
|
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 |
|
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
|
|
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 |
|
Then run the server:
1
|
|
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, check out my website, read my newsletter or follow me at @ruanbekker on Twitter.