django分页

Posted 人生苦短,我用python

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django分页相关的知识,希望对你有一定的参考价值。

django提供的分页器实现分页

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def category(request,category_id):
    # raise ValueError
    categories = models.Category.objects.filter(set_as_top_menu=True)

    if category_id == "all":
        articles = models.Article.objects.all().order_by("-id")
    else:
        articles = models.Article.objects.filter(category_id=category_id).order_by("-id")

    paginator = Paginator(articles, 2)  # 每页显示的个数

    page = request.GET.get(page)#总页数
    try:
        objs = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        objs = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        objs = paginator.page(paginator.num_pages)

    return render(request,index.html, {"categories":categories, "articles":objs})

html

              
        {% load bbs_tags %}
        <nav aria-label="..."> <ul class="pagination"> {% for page in articles.paginator.page_range %} {% if articles.number == page %} <li class="active"><a href="?page={{ page }}">{{ page }} <span class="sr-only">(current)</span></a></li> {% else %} {% render_paginator_btn articles page %} {% endif %} {% endfor %} </ul> </nav>

bbs_tags

@register.simple_tag
def render_paginator_btn(articles,page):
    current_page = articles.number
    total_page = articles.paginator.num_pages
    display_count = 7#总页数
    if current_page - 0 < 4 and page <= display_count:
        return mark_safe(<li><a href="?page={page}">{page}</a></li>.format(page=page))
    elif total_page - current_page < 3 and page > total_page - display_count:
        return mark_safe(<li><a href="?page={page}">{page}</a></li>.format(page=page))
    elif abs(page - current_page) < 4:
        return mark_safe(<li><a href="?page={page}">{page}</a></li>.format(page=page))
    return ‘‘

 

以上是关于django分页的主要内容,如果未能解决你的问题,请参考以下文章

django实现分页功能

Django REST框架分页的jQuery代码

modx - 当我在同上片段中使用“&documents =”参数时,分页不起作用

Django—分页器与form组件

在 Django 中为不同视图共享相同的分页代码

Django rest_framewok框架的基本组件