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):
First of all I would change the following:
try:
blogs = paginator.page(page)
except(EmptyPage, InvalidPage):
blogs = paginator.page(page) # Raises the same error
But you could pass a range within your context.
index = paginator.page_range.index(blogs.number)
max_index = len(paginator.page_range)
start_index = index - 3 if index >= 3 else 0
end_index = index + 3 if index <= max_index - 3 else max_index
page_range = paginator.page_range[start_index:end_index]
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:
def blog(request):
paginator = Paginator(Blog.objects.all(), 1)
try:
page = int(request.GET.get('page', '1'))
except:
page = 1
try:
blogs = paginator.page(page)
except(EmptyPage, InvalidPage):
blogs = paginator.page(1)
# Get the index of the current page
index = blogs.number - 1 # edited to something easier without index
# This value is maximum index of your pages, so the last page - 1
max_index = len(paginator.page_range)
# You want a range of 7, so lets calculate where to slice the list
start_index = index - 3 if index >= 3 else 0
end_index = index + 3 if index <= max_index - 3 else max_index
# Get our new page range. In the latest versions of Django page_range returns
# an iterator. Thus pass it to list, to make our slice possible again.
page_range = list(paginator.page_range)[start_index:end_index]
return render(request, 'blogs.html', {
'blogs': blogs,
'page_range': page_range,
})
So now we have to edit your template to accept our new list of page numbers: