Search code examples
pythondjangodjango-taggit

Django iterate queryset just n number of times in templates


My issue is quite simple. I am using Django taggit.

I want to iterate this only 2 times. Means to display only 4 tags in templates.

 {% for tag in data.tags.all %}
     {{tag}}                            
 {% endfor %}

I have tried this, but it is not making any sense:

 {% for tag in data.tags.all|ljust:"2" %}
    {{tag}}                            
 {% endfor %}

Can anyone suggest how can I achieve it?


Solution

  • You can make use of the |slice template filter [Django-doc]:

    {% for tag in data.tags.all|slice:':2' %}
        {{ tag }}                            
    {% endfor %}