欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python3之Django Web框架分页多页码处理二

程序员文章站 2022-07-03 23:26:54
...

视图函数:

 if request.method == 'GET':
    publisher_list = models.Publisher.objects.all()

    # 分页功能
    paginator = Paginator(publisher_list, 5)
    page_num = request.GET.get('page', 1)
    ##############################################
    currentPage = int(page_num)
    #  如果页数多时,换另外一种显示方式
    if paginator.num_pages > 30:
        if currentPage - 5 < 1:
            pageRange = range(1, 11)
        elif currentPage + 5 > paginator.num_pages:
            pageRange = range(currentPage - 5, paginator.num_pages + 1)

        else:
            pageRange = range(currentPage - 5, currentPage + 5)

    else:
        pageRange = paginator.page_range

    publisher_list = paginator.page(currentPage)
    context = {'publisher_list': publisher_list, 'currentPage': currentPage, 'pageRange': pageRange}

    return render(request, 'publisher.html', context)

模板代码:

{#多分页实现方式二#}
            {% for page_index in pageRange %}
                {#完整功能#}
                {% if currentPage == page_index %}

                    <li class="active"><a href="/CMS/publisherpage/?page={{ page_index }}">{{ page_index }}</a></li>

                    {% else %}
                    <li><a href="/CMS/publisherpage/?page={{ page_index }}">{{ page_index }}</a></li>
                {% endif %}
            {% endfor %}