• 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 ''
  • 相关阅读:
    MyBatis总结六:resultMap详解(包含多表查询)
    MyBatis总结五:#{}和${}的用法和区别
    MyBatis总结四:配置文件xml详解
    MyBatis使用动态代理报 invalid bound statement (not found) 错
    MyBatis总结三:使用动态代理实现dao接口
    MyBatis总结二:增删改查
    session详解&和cookie的区别
    cookie详解
    C#属性器Get和Set
    ORM实例介绍
  • 原文地址:https://www.cnblogs.com/hongpeng0209/p/6699067.html
Copyright © 2020-2023  润新知