提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
基于django的Paginator和Page类展示固定的页码数,例如在前一页和后一页之间只展示固定的10页!
一、Django+paginator分页显示固定的页数
二、代码
1.后端代码
class CommonViewMixin:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
if context["page_obj"] and context["paginator"]:
page_len = context["paginator"].num_pages - context["page_obj"].number + 1
if page_len <= self.page_control:
middle_page = range(context["page_obj"].number, context["paginator"].num_pages+1)
else:
middle_page = range(context["page_obj"].number, context["page_obj"].number + self.page_control)
context.update({
'middle_page': middle_page,
})
return context
class IndexView(CommonViewMixin, ListView):
queryset = Score.objects.all()
template_name = 'score/score_list.html'
paginate_by = 2
context_object_name = 'score_list'
page_control = 10
2.前端代码
{% if page_obj %}
{% if page_obj.has_previous %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.previous_page_number }}">前一页</a>
</li>
{% endif %}
{% for num in middle_page %}
{% if page_obj.number != paginator.num_pages %}
<li class="page-item"><a class="page-link" href="?page={{ num }}">{{ num }}</a></li>
{% endfor %}
{% if page_obj.has_next %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.next_page_number }}">后一页</a>
</li>
{% endif %}
{% endif %}
总结
Django+paginator分页显示固定的页数
|