Login

Filter to adjust forloop.counter across pages in a paginated view

Author:
egmanoj
Posted:
March 23, 2009
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

Update:

Never mind. See dc's comment below for a much easier way to do this.

I recently had to write a template for a paginated view which displayed a serial number for each object in the object_list. I normally use forloop.counter for general purpose serial numbers. However this did not work with paginated views as the counter gets reset in each page. This caused the serial numbers to go from 1 to #-of-results-in-the-page and then repeat.

Assumptions:

The adjust_for_pagination filter adjusts the value of forloop.counter based on the current page. Page and is_paginated variables are expected to be present in the context. These should respectively denote the current page number (1 based) and if the results are paginated. RESULTS_PER_PAGE is currently taken from the settings file. I couldn't think of a way to pass this value also from the template.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
from django import template
from django.conf import settings

register = template.Library()

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

# And the template snippet:
{% for object in object_list %}
<div class="serial-no">
    {% if is_paginated %}
        {{ forloop.counter|adjust_for_pagination:page }}
    {% else %}
       {{ forloop.counter }}
    {% endif %}
</div>
...
{% endfor %}

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

dc (on March 26, 2009):

Can be achieved with:

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

#

egmanoj (on March 29, 2009):

And the Truth shall set you free.

Thanks for pointing that out. I'll have fun removing that code from my repo ;)

#

Please login first before commenting.