美文网首页
django - 分页

django - 分页

作者: _琳哥 | 来源:发表于2018-01-23 15:04 被阅读102次

    包:django.core.paginator

    Paginator对象
    • Paginator(列表,int):返回分页对象,参数为列表数据,每页数据的条数
    属性
    • count:对象总数
    • num_pages:页面总数
    • page_range:页码列表,从1开始,例如[1, 2, 3, 4]
    方法
    • page(num):下标以1开始,如果提供的页码不存在,抛出InvalidPage异常
    异常exception
    • InvalidPage:当向page()传入一个无效的页码时抛出
    • PageNotAnInteger:当向page()传入一个不是整数的值时抛出
    • EmptyPage:当向page()提供一个有效值,但是那个页面上没有任何对象时抛出
    Page对象
    创建对象
    • Paginator对象的page()方法返回Page对象,不需要手动构造
    属性
    • object_list:当前页上所有对象的列表
    • number:当前页的序号,从1开始
    • paginator:当前page对象相关的Paginator对象
    方法
    • has_next():如果有下一页返回True
    • has_previous():如果有上一页返回True
    • has_other_pages():如果有上一页或下一页返回True
    • next_page_number():返回下一页的页码,如果下一页不存在,抛出InvalidPage异常
    • previous_page_number():返回上一页的页码,如果上一页不存在,抛出InvalidPage异常
    • len():返回当前页面对象的个数
    • 迭代页面对象:访问当前页面中的每个对象
    例子
    • view
    def hero_list(request, pindex):
        if pindex == '':
            pindex = '1'
        heroinfo_list = HeroInfo.objects.all()
        paginatior = Paginator(heroinfo_list, 5)
        page = paginatior.page(int(pindex))
        context = {'page': page}
        return render(request, 'booktest/herolist.html', context)
    
    • templates
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <ul>
    {% for hero in page %}
    <li>{{ hero.h_name }}</li>
    {% endfor %}
    </ul>
    <hr/>
    {% for index in page.paginator.page_range %}
        {% if index == page.number %}
            {{ index }}
        {% else %}
        <a href="/heroList/{{ index }}">{{ index }}</a>
        {% endif %}
    {% endfor %}
    </body>
    </html>
    
    image.png

    相关文章

      网友评论

          本文标题:django - 分页

          本文链接:https://www.haomeiwen.com/subject/reusaxtx.html