Вопрос

I am using django-pagination to paginate my object list. It is working flawlessly. I want to give a number to each object on the page and I am using {{forloop.counter}} for that, but the problem is it starts the object count from 1 on each page. I wanted to display the actual object count.

Say if I am paginating 10 objects per page, then I want to object number as 11 for the first object on page 2. I tried writing a template filter for this, but somehow I am not able to send both request.get.page and {{forloop.counter}} to my filter function. I am unable to do it that way.

Any help for direction will be appreciated.

Это было полезно?

Решение

You can use the add template tag to add the current count from the paginator to the forloop

{{ forloop.counter|add:paginator.page.start_index }}

Другие советы

I have used this in my template and its working properly

{{ page_obj.start_index|add:forloop.counter0 }}

Or you can use

 {% for obj in obj_list %}
     {{ forlopp.counter0|add:obj_list.start_index }}
 {% endfor %}

add paginator start index with for loop counter starting from zero

in template

{% for object in page_objects %}
    ...
    {{ forloop.counter0|add:page_objects.start_index }}
    ...
    ...
{% endfor %}

in view

objects = Abcdef.objects.all() # Abcdef is the modal
paginator = Paginator(objects, 10)
page_number = request.GET.get('page')
try:
    page_objects = paginator.page(page_number)
except PageNotAnInteger:
    page_objects = paginator.page(1)
except EmptyPage:
    page_objects = paginator.page(paginator.num_pages)    
data = {
    "page_objects" : page_objects,
}
return render(request, "template/template.html", data)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top