from django import template
register = template.Library()
@register.inclusion_tag('pagination.html')
def show_pagination(pagination, request, get_param_name):
"""
pagination : ObjectPaginator from the view
request : needed to keep get variables
get_param_name : tell which parameters to use in links/request.GET
All variables are set here for the template rendering.
You will maybe not needs all for your own template.
"""
if(request.GET.has_key(get_param_name)):
current_page = int(request.GET[get_param_name])
else:
current_page = 0
has_previous = pagination.has_previous_page(current_page)
has_previous_previous = pagination.has_previous_page(current_page-1)
has_next = pagination.has_next_page(current_page)
has_next_next = pagination.has_next_page(current_page+1)
need_pagination = has_previous or has_next
has_start_page = current_page > 2
has_end_page = (pagination.pages - current_page) > 3
has_start_hellip = current_page > 3
has_end_hellip = (pagination.pages - current_page) > 4
total_pages = pagination.pages
get_params = ''
for key, value in request.GET.iteritems():
if not key == get_param_name:
if get_params == '':
get_params = '?'+key+'='+str(value[0])
else:
get_params += '&'+key+'='+str(value[0])
if get_params == '':
get_params = '?'+get_param_name+'='
else:
get_params += '&'+get_param_name+'='
return locals()
'''An example for pagination.html file :'''
{% load math_filters %}
{% if need_pagination %}
{% if has_start_page %}1{% endif %}
{% if has_start_hellip %}…{% endif %}
{% if has_previous_previous %}{{ current_page|sub:1 }}{% endif %}
{% if has_previous %}{{ current_page }} {% endif %}
[{{ current_page|add:1 }}]
{% if has_next %} {{ current_page|add:2 }}{% endif %}
{% if has_next_next %} {{ current_page|add:3 }}{% endif %}
{% if has_end_hellip %}…{% endif %}
{% if has_end_page %}{{ total_pages }}{% endif %}
{% endif %}
'''Note that this template use this stupid sub filter :'''
from django import template
register = template.Library()
def sub(value, arg=None):
return value-arg
register.filter('sub', sub)
'''An example for the view :'''
from django.core.paginator import ObjectPaginator, InvalidPage
if request.GET.has_key('page_members'):
page_users = int(request.GET['page_members'])
else:
page_users = 0
users = User.objects.order_by('-last_login')
users_paginator = ObjectPaginator(users, 5)
users = users_paginator.get_page(page_users)
'''Code example of the template tag :'''
{% load pagination_filters %}
{% show_pagination users_paginator request "page_members" %}