CommonLounge Archive

Django Templates

May 17, 2018

Time to display some data! Django gives us some helpful built-in template tags for that.

What are template tags?

You see, in HTML, you can’t really write Python code, because browsers don’t understand it. They know only HTML. We know that HTML is rather static, while Python is much more dynamic.

Django template tags allow us to transfer Python-like things into HTML, so you can build dynamic websites faster. Cool!

Display post list template

In the previous chapter we gave our template a list of posts in the posts variable. Now we will display it in HTML.

To print a variable in Django templates, we use double curly brackets with the variable’s name inside, like this:


{{ posts }}

Try this in your blog/templates/blog/post_list.html template. Replace everything from the second <div> to the third <div> with{{ posts }}. Save the file, and refresh the page to see the results:

As you can see, all we’ve got is this:

<QuerySet [<Post: My first post>, <Post: Second post>, <Post: Post 3>, <Post: Post 4>]>

This means that Django understands it as a list of objects. Remember from Introduction to Python how we can display lists? Yes, with for loops! In a Django template you do them like this:

{% for post in posts %}
    {{ post }}
{% endfor %}

Try this in your template.

It works!

But we want the posts to be displayed like the static posts we created earlier in the Introduction to HTML chapter. You can mix HTML and template tags. Our body will look like this:


    <h1><a href="/">My Blog</a></h1>
{% for post in posts %}
        <p>published: {{ post.published_date }}</p>
        <h1><a href="">{{ post.title }}</a></h1>
        <p>{{ post.text|linebreaksbr }}</p>
{% endfor %}

Everything you put between {% for %} and {% endfor %} will be repeated for each object in the list. Refresh your page:

Have you noticed that we used a slightly different notation this time ({{ post.title }} or {{ post.text }})? We are accessing data in each of the fields defined in our Post model. Also, the |linebreaksbr is piping the posts’ text through a filter to convert line-breaks into paragraphs.

Let’s do a quick question to check your understanding before moving on to the next section.

Congrats! Step away from your computer for a bit – you have earned a break. :)

© 2016-2022. All rights reserved.