Django paginator page range for not displaying all

2020-07-11 09:49发布

I have a pagination in my site but it shows me every page like 1-19, i only want to display only 5 pages.enter image description here

How can i do this?

views.py

    paginator = Paginator(object_list, new_number_of_list)

    page = request.GET.get('page')

    try:
        Items = paginator.page(page)
    except PageNotAnInteger:
        Items = paginator.page(1)
    except EmptyPage:
        Items = paginator.page(paginator.num_pages)

    variables = RequestContext(request, {"Items": Items,
                                         "ForItemCount": ForItemCount,
                                         "page": page,
                                         })
    return render(request, 'templates/Core/resource_base.html',
                           variables)

my pagination.html

<div class="pagination p1">
  <span class="step-links">
    <ul>

          {% for l in  Items.paginator.page_range %}
            <li><a href="?page={{forloop.counter}}">{{forloop.counter}}</a></li>
          {% endfor %}



    </ul>
  </span>
</div>

3条回答
Explosion°爆炸
2楼-- · 2020-07-11 10:33

You already have the {{ forloop.counter }} in there, you can use that to limit it to five.

      {% for l in  Items.paginator.page_range %}
        {% if forloop.counter < 5 %}
            <li><a href="?page={{forloop.counter}}">{{forloop.counter}}</a></li>
        {% endif %}
      {% endfor %}

Here is another solution, which might give you some more options if you're interested: Django Pagination Display Issue: all the page numbers show up.

And finally, here is a very nice tutorial on getting up to speed with the pagination that django offers out of the box: https://simpleisbetterthancomplex.com/tutorial/2016/08/03/how-to-paginate-with-django.html.

查看更多
Melony?
3楼-- · 2020-07-11 10:39

See if https://medium.com/@sumitlni/paginate-properly-please-93e7ca776432 helps. The code uses 10 for "neighbors" but you could change it to 5 when using the tag.

查看更多
混吃等死
4楼-- · 2020-07-11 10:47

Another quick solution that can be used(+ and - 5 limit for example):

{% for l in  Items.paginator.page_range %}
    {% if l <= Items.number|add:5 and l >= Items.number|add:-5 %}
        <li><a href="?page={{forloop.counter}}">{{forloop.counter}}</a></li>
    {% endif %}
{% endfor %}
查看更多
登录 后发表回答