Skip to content

Instantly share code, notes, and snippets.

@MasterAlish
Last active August 29, 2015 14:18
Show Gist options
  • Save MasterAlish/f19a7544f41b5d581a9a to your computer and use it in GitHub Desktop.
Save MasterAlish/f19a7544f41b5d581a9a to your computer and use it in GitHub Desktop.
Paginate every models list page
# define in settings.py to able to use request in templates
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.contrib.auth.context_processors.auth',
)
# in templatetags
@register.inclusion_tag("gist:pagination_pages.html")
def pages(queryset, request):
page = int(request.REQUEST.get("page", 1))-1
n = int(request.REQUEST.get("per_page", 20))
count = queryset.count()
pages_count = count/n
if count % n > 0:
pages_count += 1
return {'pages': pagination(pages_count, page+1), 'per_page': n, 'current_page': page+1, 'last':pages_count}
def pagination(total, page=1, neighbour_count=2):
result = []
if page-neighbour_count > 2:
result.append('first')
if page-neighbour_count == 2:
result.append(1)
for i in range(page-neighbour_count, page+neighbour_count+1):
if 0 < i <= total:
result.append(i)
if page+neighbour_count < total-1:
result.append('last')
if page+neighbour_count == total-1:
result.append(total)
return result
@register.filter
def paginate(queryset, request):
page = int(request.REQUEST.get("page", 1))-1
n = int(request.REQUEST.get("per_page", 20))
return queryset[page*n:page*n+n]
{% pages articles request %} <!-- here pages will appear-->
...
{% for article in articles|paginate:request %} <!-- -->
...
{% endfor %}
<style>
.pagination {
font: 14px/24px sans-serif;
}
.page {
display: inline-block;
padding: 0px 9px;
border-radius: 3px;
border: solid 1px #c0c0c0;
background: #e9e9e9;
box-shadow: inset 0px 1px 0px rgba(255, 255, 255, .8), 0px 1px 3px rgba(0, 0, 0, .1);
font-size: .875em;
font-weight: bold;
text-decoration: none;
color: #717171;
text-shadow: 0px 1px 0px rgba(255, 255, 255, 1);
}
.page:hover {
background: #fefefe;
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#FEFEFE), to(#f0f0f0));
background: -moz-linear-gradient(0% 0% 270deg, #FEFEFE, #f0f0f0);
}
.page.active {
border: none;
background: #616161;
box-shadow: inset 0px 0px 8px rgba(0, 0, 0, .5), 0px 1px 0px rgba(255, 255, 255, .8);
color: #f0f0f0;
text-shadow: 0px 0px 3px rgba(0, 0, 0, .5);
}
</style>
<div class="pagination">
{% for page in pages %}
{% if page == current_page %}
<span class="page active">{{ page }}</span>
{% else %}
{% if page == 'first' %}
<a href="?page={{ 1 }}&per_page={{ per_page }}" class="page"> первая </a>
{% elif page == 'last' %}
<a href="?page={{ last }}&per_page={{ per_page }}" class="page"> последняя </a>
{% else %}
<a href="?page={{ page }}&per_page={{ per_page }}" class="page">{{ page }}</a>
{% endif %}
{% endif %}
{% endfor %}
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment