分页器制作(了解)
后端
def book(request):
# 分页
# 当前页数
current_page = int(request.GET.get('page', 1))
# 每页展示多少条
per_page_num = 10
# 起使位置
start_page = (current_page - 1) * 10
# 结束位置
end_page = current_page * 10
# 取出所有数据
book_all = models.Book.objects.all()
# 这个是总数据条数
all_count = book_all.count()
# page_num是总页数
'''如果more不为0的话,说明页数不够显示,要再加一页'''
page_num, more = divmod(all_count, per_page_num)
if more:
page_num += 1
page_html = ''
'''
下一步是为了因为小于6的数字不高亮显示,符合条件是current_page一定小于6时,xxx把current_page
的值接收了,然后下面在判断的时候用xxx判断,小于6的也高亮,当大于6时,xxx就不重要了,不会走if current_page < 6:
这一步,此时current_page==i时也会高亮,又因为current_page=xxx,所以判断放xxx也行
'''
xxx = current_page
# 防止页码出现负数
if current_page < 6:
current_page = 6
# 给前端显示页码
for i in range(current_page - 5, current_page + 6):
if xxx == i:
# 加高亮
page_html += '<li class="active"><a href="?page=%s">%s</a></li>' % (i, i)
else:
page_html += '<li><a href="?page=%s">%s</a></li>' % (i, i)
book_list = models.Book.objects.all()[start_page:end_page]
return render(request, 'book.html', locals())
前端
# body内
{% for book_obj in book_list %}
<p>{{ book_obj.title }}</p>
{% endfor %}
<nav aria-label="Page navigation">
<ul class="pagination">
<li>
<a href="#" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
{{ page_html|safe }}
<li>
<a href="#" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</nav>