Django Template tags: Add Dynamic data through Django Template Tags? (Part XIII)

In this tutorial, we are going to learn what Django template tags and how to use it to display the dynamic data we have stored in the database on the main website, rather than just static HTML files. So let’s start learning how to add Dynamic data through Django template tags.

This tutorial is a part of our series on Creating Blog Website using Django.

Link to the previous tutorial:

Introduction to Django Template Tags

As you might know, web browsers like Google Chrome and Safari understand and interpret only HTML files. This thing causes a problem when we want to use static python files but cannot really make the browser interpret it because HTML works only with static documents.

Django provides a workaround for this, Template tags allow us to transfer the Dynamic python data into the websites; to make much more interactive dynamic websites.

How to Implement Django Template Tags

To add a variable to showcase on the website; you need to put it inside two curly brackets for Django Template tag to recognise it in the HTML document. Something like,

{{ orderedpost }}

(Remember we have created “orderedpost” as an instance of published posts. For more information, check out: How to add data from Queryset into Templates?(Part XII) )

Then, since Django treats the variable as a list of posts, we need to use a loop in order to display the posts separately, much like :

{% for post in orderedpost %}
    {{ post }}
{% endfor %}

Now, open the blog1/templates/blog1/post.html file; and create a new division.

In that division, create a loop in order to display the title, text and published date of a post separately.

Therefore, now your HTML document would look something like :

<html>
    <head>
        <title>Django blog</title>
    </head>
    <body>

        <div>
    <h1>Django Blog</h1>
</div>

{% for post in orderedpost %}
    <div>

        <h2>{{ post.title }}</h2>
        <p>{{ post.text|linebreaksbr }}</p>
        <p>published: {{ post.published_date }}</p>
    </div>
{% endfor %}
    </body>
</html>

Now, open up the terminal and run the local web server on your machine.

Open up the web browser and your Website would look something like :

add dynamic data through django template tags

output

Hurray! That’s your first Django project.

For better understanding have a look at the whole series.

Finally, you can now host your web application online. To learn how to host your website online follow this below tutorial:

Further, feel free to drop your queries in the comments section below.

Also, have a look at other posts :

Deep Copy in python – Modify Copied list without changing original list

Watermark image using opencv in python

Leave a Reply

Your email address will not be published. Required fields are marked *