For loops in Django

anuragrana

Anurag Rana

Posted on August 14, 2019

For loops in Django

Originally published at pythoncircle.com

Demo of the code used below: DjangoTemplateFiddle.com

For loop is used to iterate over any iterable object, accessing one item at a time and making it available inside the for loop body.

For example, if you want to create a drop down of countries in Django template, you can use the below code.

{% for country in country_list %}
    <option name="{{country}}">{{country|title}}</option>
{% endfor %}

To iterate over a dictionary of people's name and their age, just like you would do in Python, use below code.

{% for name, age in data.items %}
    Name: {{name}}, Age: {{age}} <br>
{% endfor %}

Checking if iterable used in for loop is empty:

Let's say you want to display new messages to logged-in user. You fetched all the new messages from the database and stored them in a list and passed to render function along with the template.

Now you can either check if the message list is empty or not and then display the message accordingly. Example:

{% if messages %}
    {% for message in messages %}
        {{ message }}<br>
    {% endfor %}
{% else %}
    <div>No new message for you</div>
{% endif %}

Or you can use {% empty %} tag along with {% for %} tag as below.

{% for message in messages %}
    {{ message }}
{% empty %}
    <div>No new message for you</div>
{% endfor %}

Break in Django for loop:

That might be a piece of bad news for you. There is no break statement in Django template For loop.

Depending on your requirement you can do one of the following.

Option 1 - Iterate over the whole list but do not perform any action if the condition is not matched.

For example, you are printing numbers from a list and you need to exit the list as soon as number 99 is encountered. Normally this would be done as below in Python.

for number in numbers:
    if 99 == number:
        break
    print(number)

But there is no break statement in Django template For loop. You can achieve the same functionality (almost) as below.

{% set isBreak = False %}
{% for number in numbers %}
    {% if 99 == number %}
        {% set isBreak = true %}
    {% endif %}

    {% if isBreak %}
        {# this is a comment. Do nothing. #}
    {% else %}
        <div>{{number}}</div>
    {% endif %}
{% endfor %}

Option 2 - You can create your own custom template tag.

You can experiment with Django template or can create your own fiddle and share with others. Django Template Fiddle.

💖 💪 🙅 🚩
anuragrana
Anurag Rana

Posted on August 14, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related