Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Django Bootstrap paginaton
<ul class="pagination">
{% if prev %}
<li><a href="{% page_url prev %}">&laquo;</a></li>
{% else %}
<li class="disabled"><span>&laquo;</span></li>
{% endif %}
{% if show_first %}
<li><a href="{% page_url 1 %}">1</a></li>
<li class="disabled"><span>...</span></li>
{% endif %}
{% for pagenum in page_numbers %}
{% ifequal pagenum page_obj.number %}
<li class="active"><span>{{ pagenum }}</span></li>
{% else %}
<li><a href="{% page_url pagenum %}">{{ pagenum }}</a></li>
{% endifequal %}
{% endfor %}
{% if show_last %}
<li class="disabled"><span>...</span></li>
<li><a href="{% page_url 'last' %}">{{ paginator.num_pages }}</a></li>
{% endif %}
{% if next %}
<li><a href="{% page_url next %}">&raquo;</a></li>
{% else %}
<li class="disabled"><span>&raquo;</span></li>
{% endif %}
</ul>
# -*- coding: utf-8 -*-
from django import template
from django.utils.http import urlencode
register = template.Library()
@register.simple_tag(takes_context=True)
def page_url(context, page):
args = dict(context['request'].GET.items())
args['page'] = page
return '?' + urlencode(args)
@register.inclusion_tag('inc/paginator.html', takes_context=True)
def paginator(context, adjacent_pages=2):
page_obj = context['page_obj']
request = context['request']
paginator = page_obj.paginator
start_page = page_obj.number - adjacent_pages
if start_page <= 3: start_page = 1
end_page = page_obj.number + adjacent_pages
if end_page >= paginator.num_pages - 2: end_page = paginator.num_pages
page_numbers = range(start_page, end_page+1)
return {
'page_obj': page_obj,
'paginator': paginator,
'page_numbers': page_numbers,
'show_first': 1 not in page_numbers,
'show_last': paginator.num_pages not in page_numbers,
'request': request,
'prev': page_obj.previous_page_number() if page_obj.has_previous() else None,
'next': page_obj.next_page_number() if page_obj.has_next() else None,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.