Web development with python #2 : Templating jinja2 and Method POST on routing system

in #utopian-io6 years ago (edited)

Repository

https://github.com/python

What Will I Learn?

  • Templating jinja2
  • Pass the parameter to the template
  • POST data on the routing system

Requirements

  • Basic Python
  • Install Python 3
  • Install Flask

Resources

Difficulty

Basic

Tutorial Content

This tutorial is a continuation of the previous tutorial series, in previous tutorials, we have learned how to install and routing systems on the flask. well in this tutorial we will learn new things, we will learn how to use the templating system on the flask. Well, the flask has a templating system, jinja2 and not only that we will also learn how to use the post method on the flask. for those of you who don't know the flask, I suggest you follow my tutorial before, let's just start our tutorial.

Templating jinja2

When we install the flask, we can automatically use the templating system of the jinja2, with this templating system we can easily render HTML templates. Not only can you render HTML later in the template, but we can also use the logic of the program logic in our templates, such as looping, if else etc.

-Create templates directory

We will start by creating a folder directory to save our templates. so we can more easily access it. I will create a folder with the name templates.

Screenshot_2.png

so we will save all of our templates in the templates folder

  • Use template in route

We have created our template directory. now we will use it in our routing system. We can render our HTML template with use function render_template().for more details, you can see the code like this:

app.py

// import module
from flask import Flask, render_template

//defined flask
app = Flask(__name__)

//route
@app.route('/welcome')
def myFunction():
        return render_template('index.html');
  • Because we will use the render_template() function we must import it first like this from flask import Flask, render_template

  • to use it we can pass the name of our HTML file in the render_template function like this render_template('index.html')

  • index.html is the file that we created in the templates folder. the contents are as follows.

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Template Jinja2</title>
</head>

<body>
    <h1 style="color:red;">Hi all member of utopian , I'm new</h1>
</body>
</html>

to see the results we can run our code and the results will be as shown below:

ezgif.com-video-to-gif.gif

We can see in the picture above we have successfully rendered the HTML file on our application. now we will learn how to pass data on our template

  • Passing data to templates

We are still learning about the template, in the previous section, we have successfully rendered the template in our routing system, but the template is still dynamic. well in this section we will learn how to pass dynamic data to our templates. for more details, we can see the code below:

app.py

// import module
from flask import Flask, render_template

//defined flask
app = Flask(__name__)

//routing
@app.route('/welcome/<user>')
def paramFunc(user):
        return render_template('profile.html', userData = user);
  • We have learned how to pass a parameter to routing in the previous tutorial, now we will pass the parameter to the data that will be received in our template.

  • to pass parameters to the template we can put them in the second parameter and we can give a new name to throw in the template like the following render_template('profile.html', userData = user);. user is data that we get from routing parameters and userData is a new name that will be used in the profile.html template, you can use the same or different names. No problem...

  • We can create a new template, namely profile.html. The contents are like the following:

profile.html

<!DOCTYPE html>
<html>
<head>
    <title>Template Jinja2</title>
</head>

<body>
    <h1>This is the profile page</h1>
    <h2 style="color:blue;">Hai my name is {{userData}}</h1>
</body>
</html>

We can print the data we get from routing with {{nameOfdata}}. to see the results we can see in the picture below:

ezgif.com-video-to-gif (1).gif

We can see in the picture above we have successfully rendered the data that we pass in the template.

Post method

In web applications, of course, we will use methods such as get, post, put, delete. in this section we will learn how to use these methods in our routing system. but before we use these methods, for example, I will create a login form. I will make a new routing on our application, That is /login. I will create a login page with the name login.html, you can see the contents like this:

login.html

<!DOCTYPE html>
<html>
<head>
    <title>Login page</title>
</head>
<body>
    <h1>Form Login</h1>
    <form action="/login" method="post">
        <label for="">Email</label><br>
        <input type="text" name="email"><br><br>

        <label for="">Password</label><br>
        <input type="password" name="password"><br>

        <input type="submit" name="" value="login">
        
    </form>
</body>
</html>

We make a simple login using the post method. We make a simple login using the post method and will do an action to the '/login' URL <form action="/login" method="post">.

  • Create routing '/login'

We have created the form section to log in, now we will move to the routing system. In our routing system, we will create a new routing, namely '/login'.For more details, you can see at the code below:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/welcome')
def myFunction():
        return render_template('index.html');

@app.route('/welcome/<user>')
def paramFunc(user):
        return render_template('profile.html', userData = user)

@app.route('/login', methods=["GET", "POST"])
def login():
    if request.method == "POST":
        return " Your method is POST"
    
    return render_template('login.html')
  • Import function request: in the flask we can use the request method to retrieve all request data, to use it we must import it first as follows from flask import Flask, render_template, request.

  • Defined the method in route: in the routing flask system we can define what method we will use in the routing in the following way @app.route('/login', methods=["GET", "POST"]). We can define the routing method in the second parameter with key methods = ["GET", "POST"]. Because the method we use more than one we can have to be defined in the form of an array[].

  • Handle multiple methods: We can use several methods in the same routing, to distinguish it we can use request.method and use if else to distinguish the action that will be used. We will make an example like the following:

if request.method == "POST":
    return " Your method is POST"
    
return render_template('login.html')

If the method used is POST we will do return " Your method is POST". If the method is not POST which means the method is GET, then we will render the login.html template. We can see an example like the picture below:

ezgif.com-video-to-gif (2).gif

We can see in the image above, the routing that we access the same. but have two different conditions when we access different methods. when the GET method, we will render return render_template('login.html'). but if we use the POST method we will return " Your method is POST"

  • Get value from POST data

Now we will learn how to get the data we POST. we can use the request function that we have seen before. because the data we post on our form can use the request.form method. for more details, we can see the code below:

app.py

@app.route('/login', methods=["GET", "POST"]) // the method we used
def login():
    if request.method == "POST":
        return "Your email is "+ request.form['email']
    
    return render_template('login.html')
  • to get the data we post we can use request.form['nameOfinput']. in this tutorial, we will try to retrieve data that is post through <input type="text" name="email">. the name of input is 'email', so we can get the value like this request.form['email']. to see the results we can see in the picture below:

ezgif.com-video-to-gif (3).gif

We see in the picture above we have successfully retrieved the post data, this is something very important when we want to interact with user data, we have learned new things in this tutorial, I hope you can this tutorial can be the basis for you to know the flask to be developed into better. thank you for following this tutorial...

Curriculum

Web developement with python #1 : Flask initialization and Routing system

Proof of work done

https://github.com/milleaduski/python-web-app

Sort:  

Thank you for your contribution.

  • Nice to see a continuation of your prior tutorial.
  • It's also nice to learn about Jinja2, although i believe you could have shed a bit more light into it and which commands in your tutorial pertain to using it.
  • Like the prior one, I believe the tutorial is somewhat basic. I would advise you provide something more unique to the table.
  • I like the fact that you document and show screenshots of the different steps, useful to your reader.
  • I suggest you try to improve the overall language and punctuation of the post. There are some serious issues there.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thank you for your review, @mcfarhat! Keep up the good work!

Congratulations! Your post has been selected as a daily Steemit truffle! It is listed on rank 15 of all contributions awarded today. You can find the TOP DAILY TRUFFLE PICKS HERE.

I upvoted your contribution because to my mind your post is at least 9 SBD worth and should receive 98 votes. It's now up to the lovely Steemit community to make this come true.

I am TrufflePig, an Artificial Intelligence Bot that helps minnows and content curators using Machine Learning. If you are curious how I select content, you can find an explanation here!

Have a nice day and sincerely yours,
trufflepig
TrufflePig

Hey, @duski.harahap!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Hi @duski.harahap!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

When delving into the intricate world of solutions, turning to professional web design services is essential. They are the cornerstone of your online presence, guaranteeing that your website not only dazzles aesthetically but also operates flawlessly, setting the stage for a captivating user journey.