自定义分页: 灵活使用上面的 paginator 和 page 的属性值即可实现
View视图方面:
try:
current_page=request.GET.get('current_page')
current_page=int(current_page)
except Exception:
current_page=int(1)
res=models.Student.objects.all()
page=Paginator(res,10) # 对象列表 每列呈现的对象个数
current=page.page(current_page) #具体每一页的页对象 page
if (current_page <= 5): # 分页器每次显示11页
st=1
ed=st+5+5
elif current_page+5 > page.num_pages:
st=page.num_pages-5-5 # 当在最后几页的时候,越往后点后面的页数越少,但仍应当保持总的页数不变
ed=page.num_pages
else:
st=current_page-5
ed=current_page+5
return render(request,'index.html',{'current':current,'num_pages':range(st,ed+1)})
Html方面:
<nav aria-label="Page navigation">
<ul class="pagination">
<li>
{% if current.has_previous %}
<a href="/index?current_page={{ current.previous_page_number }}" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
{% endif %}
</li>
{% for i in num_pages %}
{% if i == current.number %}
<li class='active'><a href="/index?current_page={{ i }}" style="margin-right: 10px"> {{ i }} </a></li>
{# 将选中的页号加颜色显示,只需要在li标签加上一个 activate class属性即可 #}
{% else %}
<li><a href="/index?current_page={{ i }}" style="margin-right: 10px"> {{ i }} </a></li>
{% endif %}
{% endfor %}
<li>
{% if current.has_next %}
<a href="/index?current_page={{ current.next_page_number }}" aria-label="Previous">
<span aria-hidden="true">»</span>
</a>
{% endif %}
</li>
</ul>
</nav>
from django.core.paginator import Paginator,Page #导入模块
paginator=Paginator(res,10) # 将res对象列表按每页10个对象的方式分组,得到paginator
# paginator对象有一下的属性
# per_page: 每页显示条目数量
# count: 数据总个数
# num_pages:总页数
# page_range:总页数的索引范围,如: (1,10),(1,200)
# page: page对象
current=paginator.page(current_page) # 具体得到某一页的页对象
# 对于具体某一页的页对象来说又有一下属性
# has_next 是否有下一页
# next_page_number 下一页页码
# has_previous 是否有上一页
# previous_page_number 上一页页码
# object_list 分页之后的数据列表
# number 当前页
# paginator paginator对象
![](https://img-blog.csdnimg.cn/20190502011416180.png)