#前端页面分页 Paginator
#views逻辑
from django.core.paginator import Paginator
def index(request): page = request.GET.get('page') articles = models.Article.objects.all() #创建Paginator实例对象,每页展示5条数据 page_obj = Paginator(articles,5) # print("文章一共有多少数据",page_obj.count) # print("一共分了多少页",page_obj.num_pages) # print("页码列表 range对象",page_obj.page_range) # for i in page_obj.page_range: # print(i) #page_data数据是某一页的数据集合对象 page_data = page_obj.get_page(page) # print("是否有上一页或下一页",page_data.has_other_pages()) # print("是否有下一页",page_data.has_next()) # print("是否有上一页",page_data.previous_page_number()) # print("当前页",page_data.number) return render(request,'index.html',{'articles':page_data,"page_obj":page_obj})
#前端对返回数据进行处理
{% if articles.has_other_pages %}
<div class="text-center mt-2 mt-sm-1 mt-md-0 mb-3 f-16">
{% if articles.has_previous %}
<span class="text-secondary" title="当前页已经是首页"><a href="/articles?page={{ articles.previous_page_number }}">上一页</a></span>
{% endif %}
{% for num in page_obj.page_range %}
{% if num == articles.number %}
<span class="mx-2" style="background-color: #0d8ddb"><a href="/article?page={{ num }}"></a>{{ num }}</span>
{% else %}
<span class="mx-2"><a href="/articles?page={{ num }}">{{ num }}</a></span>
{% endif %}
{% endfor %}
{% if articles.has_next %}
<a class="text-success" href="/articles?page={{ articles.next_page_number }}">下一页</a>
{% endif %}