我已经使用通用ListView实现了一个paginator。我的问题是,对于包含许多页面的列表,它显示所有页码,而不是例如当前页面之前和之后的五页。有没有一种简单的方法来解决这个问题?
在views.py中:
class CarList(LoginRequiredMixin, ListView):
model = Car
paginate_by = 20
在html中:
{% if is_paginated %}
<ul class="pagination pagination-centered">
{% if page_obj.has_previous %}
<li><a href="/car?ordering={{ current_order }}&page=1"><<</a></li>
<li><a href="/car?ordering={{ current_order }}&page={{ page_obj.previous_page_number }}"><</a></li>
{% endif %}
{% for i in paginator.page_range %}
<li {% if page_obj.number == i %} class="active" {% endif %}><a href="/car?ordering={{ current_order }}&page={{i}}">{{i}}</a></li>
{% endfor %}
{% if page_obj.has_next %}
<li><a href="/car?ordering={{ current_order }}&page={{ page_obj.next_page_number }}">></a></li>
<li><a href="/car?ordering={{ current_order }}&page={{ page_obj.paginator.num_pages }}">>></a></li>
{% endif %}
</ul>
{% endif %}
答案 0 :(得分:10)
该算法并不太复杂,如果我们假设如果有超过11页(当前,5之前,之后5)我们将总是显示11个链接,则可以进一步简化。现在我们有4个案例:
考虑到上述情况,让我们修改您的视图,创建一个变量来保存要显示的页面数量并将其放在上下文中:
class CarList(LoginRequiredMixin, ListView):
model = Car
paginate_by = 20
def get_context_data(self, **kwargs):
context = super(CarList, self).get_context_data(**kwargs)
if not context.get('is_paginated', False):
return context
paginator = context.get('paginator')
num_pages = paginator.num_pages
current_page = context.get('page_obj')
page_no = current_page.number
if num_pages <= 11 or page_no <= 6: # case 1 and 2
pages = [x for x in range(1, min(num_pages + 1, 12))]
elif page_no > num_pages - 6: # case 4
pages = [x for x in range(num_pages - 10, num_pages + 1)]
else: # case 3
pages = [x for x in range(page_no - 5, page_no + 6)]
context.update({'pages': pages})
return context
现在,您只需在模板中使用新变量即可创建页面链接:
(...)
{% for i in pages %}
<li {% if page_obj.number == i %} class="active" {% endif %}><a href="/car?ordering={{ current_order }}&page={{i}}">{{i}}</a></li>
{% endfor %}
(...)