I am using the django paginator in the template. Its working ok, but not good when there's large numbers of pages.
views.py:
def blog(request):
blogs_list = Blog.objects.all()
paginator = Paginator(blogs_list, 1)
try:
page = int(request.GET.get('page', '1'))
except:
page = 1
try:
blogs = paginator.page(page)
except(EmptyPage, InvalidPage):
blogs = paginator.page(page)
return render(request, 'blogs.html', {
'blogs':blogs
})
snippet of the template:
<div class="prev_next">
{% if blogs.has_previous %}
<a class="prev btn btn-info" href="?page={{blogs.previous_page_number}}">Prev</a>
{% endif %}
{% if blogs.has_next %}
<a class="next btn btn-info" href="?page={{blogs.next_page_number}}">Next</a>
{% endif %}
<div class="pages">
<ul>
{% for pg in blogs.paginator.page_range %}
{% if blogs.number == pg %}
<li><a href="?page={{pg}}" class="btn btn-default">{{pg}}</a></li>
{% else %}
<li><a href="?page={{pg}}" class="btn">{{pg}}</a></li>
{% endif %}
{% endfor %}
</ul>
</div>
<span class="clear_both"></span>
</div>
Now it looks like this:
What do I do to display only 7 page numbers and not all of it ranging from the current page number, like this:
Prev 1 (2) 3 4 5 Next
I hope I was clear, if not please ask. Your help and guidance will be very much appreciated. Thank you.
I did it only on templates with expressions:
I know django is like "dont write your code again" but i found this easier for me to understand right now. Hope i helped.
Gonna throw this in. I came up with it because it lets you know there are more pages on either side.
And it looks like this:
Another shorter solution with template is compare current forloop.counter with certain range.
with bootstrap I use this template
screenshot
First of all I would change the following:
But you could pass a range within your context.
Now you should be able to loop over the range to construct the right links with
?page=
.=== Edit ===
So your view would be something like this:
So now we have to edit your template to accept our new list of page numbers:
You could also extend
Paginator
class.Then in template:
Now
page_range
will only consist of 7 items.wing_pages
+ current page +wing_pages
custom django paginator for bootstrapI found the simplest thing to do was to create a pagination snippet that just shows the pages you want it to.
In my case I didn't want any previous or next links. I just wanted to always have a link to the first and last pages and then have the current page and the two pages either side of the current page.
My template snippet (uses variables from django-tables2 - variables will have slightly different names if you're using a Django
Paginator
directly)Examples of what my pagination looks like at different pages
Credit: this was inspired by @Pavel1114's answer