Django手写分页

Posted zchzy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django手写分页相关的知识,希望对你有一定的参考价值。

def get(self, request, *args, **kwargs):
# 获取当前页码
pg = int(request.GET.get(‘page‘, 1))
obj = Student.objects.all().order_by("id")
# 创建分页器对象
page_obj = Paginator(obj, 3)
try:
# 获取当前页码数得数据 pg =1
page_data = page_obj.page(pg)
except PageNotAnInteger:
# 第一页
page_data = page_obj.page(1)
except EmptyPage:
# 最后一页
page_data = page_obj.page(page_obj.num_pages)

# 每页开始页码
begin = (pg - int(math.ceil(10.0 / 2)))
if begin < 1:
begin = 1
# 每页结束页码
end = begin + 9
# page_obj.num_pages 获取所有页码
print(page_obj.num_pages)
if end > page_obj.num_pages:
end = page_obj.num_pages

if end <= 10:
begin = 1
else:
begin = end - 9

pagelist = range(begin, end + 1)

return render(request, ‘index.html‘,
{‘page_obj‘: page_obj, ‘page_data‘: page_data, ‘pagelist‘: pagelist, ‘bigpage‘: pg}, )


前端代码
<div>
{% if page_data.has_previous %}
<a href="{% url ‘index‘ %}?page={{ page_data.previous_page_number }}">上一页</a>
{% endif %}
{#显示所有页码#}
{# {% for n in page_obj.page_range %}#}
{# {% if n < 6 %}#}
{# <a href="{% url ‘index‘ %}?page={{ n }}">{{ n }}</a>&emsp;#}
{# {% endif %}#}
{# {% endfor %}#}
{% for n in pagelist %}
{% if bigpage == n %}
<a href="{% url ‘index‘ %}?page={{ n }} " style="font-size: 25px; color: firebrick">{{ n }}</a>
{% else %}
<a href="{% url ‘index‘ %}?page={{ n }}">{{ n }}</a>
{% endif %}
{% endfor %}

{% if page_data.has_next %}
<a href="{% url ‘index‘ %}?page={{ page_data.next_page_number }}">下一页</a>
{% endif %}
</div>

以上是关于Django手写分页的主要内容,如果未能解决你的问题,请参考以下文章

django分页后查询丢失

Django基础之django分页

Django框架(十四)—— Django分页组件

Django框架(十五)—— Django分页组件

Django基础之django分页

django视图之分页