Blog available for sell
This blog is available for sale. Please 'contact us' if interested.
Advertise with us
templates tag for-loop   0   73666
For loop in Django template


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 %}


See the demo here: https://www.djangotemplatefiddle.com/f/ekDF3p/


for is an inbuilt tag in Django template and it needs to be closed using endfor tag.



Iterating over a dictionary:

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 %}


See the demo here: https://www.djangotemplatefiddle.com/f/8G2HtW/


Objects like data and country_list will be passed to the render function while rendering the template.

return render(request, 'appname/template_name.html', {"data":data, "country_list":country_list})



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



Iterating over a reversed list:

You can iterate over a list in reverse order using below code.

{% for member in member_list_score_wise reversed %}
    {{ member }} <br>
{% endfor %}



Accessing loop index inside the loop:

If you want to print the sequence number before the item being printed, you can use forloop.counter variable.

{% for member in member_list_score_wise reversed %}
    {{forloop.counter}}. {{ member }} <br>
{% endfor %}
1. John
2. Mac
3. Tony


See the demo here: https://www.djangotemplatefiddle.com/f/BhWj5E/


Similarly, you can use the below variables:

forloop.counter0  - current index when started with 0
forloop.revcounter - index from last of the loop, started with 1
forloop.revcounter0 - index from last of the loop, started with 0
forloop.parentloop - parent loop index in nested For loops
forloop.first - return true if the current item is the first item of list
forloop.last - return true if the current item is the last item of the list



Range in Django template:

Sometimes you just need to run a loop N number of times. In such cases item at the current index doesn't matter. In python you would use range function. But again, there is no range tag or function in Django template. You can use either one of the below approaches.

Option 1 - Pass the list to render function along with template.

render(request, template.html, {"numbers": range(100)})

And in template

{% for number in numbers %}
    {{number}}
{% endfor %}


Option 2 - You can use the below code to emulate the range function.

{% for item in "x"|ljust:"100" %}
    {{item}} {# or do anything 100 times #}
{% endfor %}

ljust left-align the values in a field of the given width (100 in this case). So "x"|ljust:"10" will be "x         ". So basically you a string of length 10 with 9 spaces in it and 'x' as the first character. Now you are iterating over this string one character at a time.


Further Readings:

https://docs.djangoproject.com/en/2.2/ref/templates/builtins/
https://www.pythoncircle.com/post/42/creating-custom-template-tags-in-django/
https://djangosnippets.org/snippets/2093/
 

templates tag for-loop   0   73666
0 comments on 'For Loop In Django Template'

Related Articles:
Using IF ELSE condition in Django template
how to use IF ELSE in Django template, Syntax of IF, ELIF and ELSE in Django, Using filters within IF condition in Django template, Multiple elif (else if) confitions in Django template...
How to display flash messages in Django templates
flash messages in Django template, one-time notifications in Django template, messages framework Django, displaying success message in Django, error message display in Django...
Django Template Fiddle Launched !!!!
Django template fiddle, Experimenting with Django templates, Playing with Django template, Django fiddle, template fiddle, djangotemplatefiddle.com,...
Solving Django Error: TemplateDoesNotExist at /app_name/
How to solve TemplateDoesNotExist error in Django projects, reason for TemplateDoesNotExist error in Django, fixing TemplateDoesNotExist error in Django...
DigitalOcean Referral Badge

© 2024-2025 Python Circle   Contact   Sponsor   Archive   Sitemap