how to set index of page range in django templates

1.8k views Asked by At

I have the following for loop that iterates over my pagination object:

{% for x in my_paginator.paginator.page_range %}
    <a href="?{% if query %}q={{ query }}&amp;{% endif %}page={{ x }}"><u>{{ x }}</u></a> 

{% endfor %}

I want to slice out 4 indices less than the current page and 4 values greater than the current page.

I can get current page like this: {{ my_paginator.number }}

How do i get a range that I can print with {{ x }} if the page number is "61" that outputs something like:

57 58 59 60 61 62 63 64 65

2

There are 2 answers

1
doniyor On

you can render the min and max limits from your views:

paginator = Paginator(yourqueryset, request.GET.get('show'))
if request.GET.get('page'):
    try:
      results = paginator.page(request.GET.get('page'))
    except PageNotAnInteger:
      results = paginator.page(1)
    except EmptyPage:
      results = paginator.page(paginator.num_pages)
else:
    results = paginator.page(1)
min = all.number - 4
max = all.number + 4
return render(request, 'template.html', {'results':results,'min':min,'max':max})

then in template like:

{% for page in results.paginator.page_range %}
   {% if page < max and page > min and page != results.number %}
      <a class="page">{{page}}</a>
   {% elif page == results.number %}
      <a>{{page}}</a>
   {% endif %}
{% endfor %}

then you will have something like:

57 58 59 60 61 62 63 64 65

0
Atma On

I ended up doing this:

{% for x in my_paginator|relative_page_list:"5" %}

                <a href="?{% if query %}q={{ query }}&amp;{% endif %}page={{ x }}"><u>{{ x }}</u></a> 

                    {% endfor %}

The template tag implementation looks like this:

from django import template
import string

register = template.Library()

@register.filter(name='relative_page_list')
def relative_page_list(paginator, page_range):
    print 'arg: '+str(page_range)
    print 'page number: '+str(paginator.number)
    page_number = paginator.number
    last_page_number = paginator.paginator.page_range[-1]
    page_range = int(page_range)
    page_min = page_number - page_range
    page_max = page_number + page_range

    print 'min: '+str(page_min)
    print 'max: '+str(page_max)

    if page_min < 0:
        page_min = 0

    if page_max > last_page_number:
        page_max = last_page_number

    print page_min
    print page_max
    return paginator.paginator.page_range[page_min:page_max]

This works exactly like Google's pagination.