How to write a For Loop in a Django Template

Subscribe to my newsletter and never miss my upcoming articles

Welcome to my .py series where I take you through what I learn weekly at She Code Africa Mentorship program Cohort 2-Python track. You can check below for other episodes.

This episode is about For Loops in Django Templates

After adding templates to your beautiful Django Project, you might want to iterate over your data and present it properly and for loops do a perfect job. You should note that the Django template has a special syntax to follow.

A For Loop is traditionally used when you have a block of code in which you want to repeat a fixed number of times (iterates over the members of a sequence in order.

  • Python Wiki

Specific to the for loop, I will be using the Django template tags {% tag %} and template variables {{ variable }} in this article. You can read more about the Django Template Language.

A template contains variables, which when the template is evaluated, and tags, which control the logic of the template.

  • Django Docs

From the blog app, we have been developing in this series, I will be iterating over the articles added from the admin section as an example of how to write a for loop in a Django template.

Let's start:

1) Add the start For Loop tag

{% for article in articles %}

2) Add the variable tag in relation with your models

{{ article.title }}

{{ article.text }}

{{ article.date }}

{{ article.author }}

{{ article.title }} will be replaced with title attribute (in models) of the article object.

3) End the For Loop tag

{% endfor %}

And that's it!

The template code should look like this:

{% for article in articles %}

 <div class="blog_text">

    <h4>{{ article.title }}</h4></a>
    <p>{{ article.text }}</p>
    <div class="date">{{ article.date }}</a>
    <a href="#">{{ article.author }}</a>

</div>

{% endfor%}

You must not be building a blog app like I am, but just follow the convention and pattern.

Let's runserver to see the beautiful work

python mange.py runserver

We have successfully looped through the articles!

Don't mind the jargon-filled articles, the blog is still in development.

Thanks for reading!

References

Ujah Emmanuel's photo

Interesting read Ruth. Look forward to see more from you. I am also learning and putting out content about Django. Would like to connect

Ruth Ikegah's photo

I'm glad it was helpful. Sure, send a message on Twitter @ikegahruth

Bolaji Ayodeji's photo

This is well written, great work!