I have a view for showing the list of news items:
def index(request, page_number=1):
news_list = get_list_or_404(NewsItem.objects.order_by('-pub_date'))
news_paginator = Paginator(news_list, 10)
return render(request, 'news/index.html', {'news_list': news_paginator.page(page_number))
As you can see, ten news items are displayed on every page.
The template:
<div class="paginator">
<ul>
<!-- Left arrow -->
{% if news_list.has_previous %}
<li class="arrow"><a class="no_underline" href="{% url 'news:index' news_list.previous_page_number %}"><b>←</b></a></li>
{% else %}
<li class="arrow unavailable"><b>←</b></li>
{% endif %}
<!-- Page numbers -->
{% for page in news_list.paginator.page_range %}
{% if page == news_list.number %}
<li class="current"><a class="no_underline" href="{% url 'news:index' page %}">{{ page }}</a></li>
{% else %}
<li><a class="no_underline" href="{% url 'news:index' page %}">{{ page }}</a></li>
{% endif %}
{% endfor %}
<!-- Right arrow -->
{% if news_list.has_next %}
<li class="arrow"><a class="no_underline" href="{% url 'news:index' news_list.next_page_number %}"><b>→</b></a></li>
{% else %}
<li class="arrow unavailable"><b>→</b></li>
{% endif %}
</ul>
</div>
It looks like this:
← 1 2 3 4 5 6 7 8 →
Let's imagine there are 217 news items, and I wouldn't like to have 21 page numbers at the bottom of the list. Instead, I'd prefer to set the limit: only 5 page numbers. But this limit has to be stable, there always should be 5 page numbers regardless the current position in the list of the pages:
← 1 2 3 4 5 →
← 11 12 13 14 15 → (in the middle of the list)
← 17 18 19 20 21 → (the last page is shown)
How can I achieve this?