Django基础06篇 分页

1.导入Django自带的分页类

from django.core.paginator import Paginator

2.分页类的使用

def index(request):
    # return HttpResponse('hello django!')
    limit = request.GET.get('limit',5)
    page_number = request.GET.get('page',1)
    articles = models.Article.objects.all()
    page = Paginator(articles,limit)  # 分页后的对象
    articles = page.page(page_number) # 当前页的数据

    print(articles.has_next())  # 有没有下一页
    # print(articles.next_page_number())#下一页的页码,有下一页的话才有
    print(articles.has_other_pages())  # 有没有其他页
    print(articles.has_previous())  # 有没有上一页
    # print(articles.previous_page_number())#上一页的页码
    print(articles.number)  # 当前页的页码
    print(articles.start_index())  # 当前这一页的第一条数据的下标
    print(articles.end_index())  # 当前这一页的最后一条数据的下标
    # articles.paginator #就是上面分页完之后的对象

    print(page.num_pages)  # 总共多少页
    print(page.page_range)  # 分页的范围  1 2 3 4
    # articles.paginator.num_pages
    # title = 'my blog'
    return render(request, 'index.html', {'articles': articles}) 

3. 前端代码中使用

<div class="text-center mt-2 mt-sm-1 mt-md-0 mb-3 f-16">
                    {% if articles.has_previous %}
                        <a class="text-success" href="?page={{ articles.previous_page_number }}">上一页</a>
                    {% else %}
                        <span class="text-secondary" title="当前页已经是首页">上一页</span>
                    {% endif %}
                    <span class="mx-2">&nbsp;{{ articles.number }}&nbsp;/&nbsp;{{ articles.paginator.num_pages }}&nbsp;</span>
                    {% if articles.has_next %}
                        <a class="text-success" href="?page={{ articles.next_page_number }}">下一页</a>
                    {% else %}
                        <span class="text-secondary" title="当前页已经是尾页">下一页</span>
                    {% endif %}


                </div>
index.html
原文地址:https://www.cnblogs.com/lhy-qingqiu/p/14089271.html