Skip to content

Instantly share code, notes, and snippets.

@leonsmith
Last active July 6, 2020 17:22
Show Gist options
  • Save leonsmith/5501345 to your computer and use it in GitHub Desktop.
Save leonsmith/5501345 to your computer and use it in GitHub Desktop.
Pagination range, used to limit huge pagination objects
from django import template
register = template.Library()
@register.filter
def pagination_range(obj, current=1, limit=10):
"""
Used with pagination page_range object when you have a lot of pages
> obj = range(100)
> pagination_limit(obj, 1)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
> pagination_limit(obj, 6)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
> pagination_limit(obj, 7)
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
> pagination_limit(obj, 9)
[4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
> pagination_limit(obj, 99)
[91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
Use within a template with a paginator:
{% for page in obj_list.paginator.page_range|pagination_limit:obj_list.number %}
{{ page }}
{% endfor %}
"""
left = (limit / 2) + 1
right = limit / 2
total = len(obj)
if limit % 2 == 0:
right -= 1
if current < left:
return obj[:limit]
if current > total - right:
return obj[total-limit:]
return obj[current-left:current+right]
@lxmmxl56
Copy link

lxmmxl56 commented Jul 2, 2020

Not sure if this is a version issue but this returned an error for me after page 6:

slice indices must be integers or None or have an __index__ method

Seems like the division might result in floats so:

35:    left = int((limit / 2) + 1)
36:    right = int(limit / 2)

@leonsmith
Copy link
Author

@lxmmxl56 this was written 7 years ago so was python 2.7 only which used int division by default 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment