Search code examples
pythondjangopaginationtemplatetags

django foorloop counter restarts in a new page


currently I'm writing a simple todolist with django. I have a view and html file for showing the list of items, and I want a number for each task in the table starting from 1. I'm using {% footloop.counter %} for that in my template.

Everything was ok until I wrote the paginator. when you choose to go to the next page, the counter starts from 1 again ,therefor the numbers in the table in each page start from one too. but I want the numbers to be continued in order until the last page. Is there any template tags or code snippets for that? Thanks in advance.

here are the codes involved:

**list.html:**

    {% for task in tasks %}
                            <tbody>
                            <tr>
                                <th scope="row" class="col-md-1">{{ forloop.counter }}</th>
                                <td class="col-md-2">{{ task.title }}</td>
                                <td class="col-md-3">{{ task.description|truncatewords:10 }}</td>
                                <td class="col-md-2">{{ task.time|date:"H:i" }} - {{ task.time|date:"D d M , Y" }}</td>
                            </tr>
                            </tbody>
    {% endfor %}



<!--Pagination-->

 {% if is_paginated %}
        <div class="container p-4">
            <div class="pagination justify-content-center">
                <span class="step-links">
                    {% if page_obj.has_previous %}
                        <a href="{% url 'home:list' 1 %}">&laquo; first</a>
                        <a href="{% url 'home:list' page_obj.previous_page_number %}">previous</a>
                    {% endif %}

                    <span class="current">
                        Page {{ page_obj.number }} of {{page_obj.paginator.num_pages }}
                    </span>

                    {% if page_obj.has_next %}
                        <a href="{% url 'home:list' page_obj.next_page_number %}">next</a>
                        <a href="{% url 'home:list' page_obj.paginator.num_pages%}">last &raquo;</a>
                    {% endif %}
                </span>
            </div>
        </div>
    {% endif %} 

Solution

  • You can try to build your own template tag and use it on the template like below :-

    @register.filter
    def adjust_for_counter(value, page):
        value, page = int(value), int(page)
        counter_value = value + ((page - 1) * settings.RESULTS_PER_PAGE)
        return counter_value
    

    and call it like below in the html :-

    {{ forloop.counter|adjust_for_pagination:page }}
    

    For more details you can refer to below link :- https://djangosnippets.org/snippets/1391/