Search code examples
djangoreversepaginator

Django reverse page object numeration


I use {{ forloop.counter0|add:page_obj.start_index }} And get (pagination 3):

Page1: 1  Page2: 4
       2         5
       3

If I use {{ forloop.revcounter0|add:page_obj.start_index }} I get:

Page1: 3  Page2: 5
       2         4
       1

How can I get:

Page1: 5  Page2: 2
       4         1
       3

I was thinking something like {{ paginator.count|add:SOMETHING }}


Solution

  • The best solution would be to write a custom template tag to do this. In some suitable app of yours make a directory templatetags.py and also add a file __init__.py in it. Inside directory make a new file in which we will write template tags lets say pagination_extras.py. After this your directory structure would look something like:

    <appname>/
        __init__.py
        models.py
        templatetags/
            __init__.py
            pagination_extras.py
        views.py
    

    Now in pagination_extras.py make a custom template tag to do this calculation for you:

    from django import template
    
    register = template.Library()
    
    @register.simple_tag
    def pagination_reverse_numbering(paginator, page_obj, loop_count):
        return paginator.count - page_obj.start_index() - loop_count + 1
    

    Now in your template you will first load this tag and then use it to perform your numbering:

    {% load pagination_extras %}
    ...
    {% for item in page_obj %}
        {% pagination_reverse_numbering paginator page_obj forloop.counter0 %}
    {% endfor %}