要一直走下去

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

一、分页器对象

from django.core.paginator import Paginator,EmptyPage

book_list = Book.objects.all() #假设有100条数据
#分页器 每页展示条数:8条
paginator = Paginator(book_list, 8) #返回Paginator对象
# print(paginator.count) #数据总条数 100
# print(paginator.num_pages) #总页数 13
# print(paginator.page_range) #页码的列表 range(1,14)

current_page = int(request.GET.get('page')) #拿到前端传的页码 url: http://localhost:8000/index?page=3

二、template中:当前页数据对象

curr_pg_obj = paginator.page(current_page) #拿到当前页的数据对象

#下面两种方式取数据
1,curr_pg_obj.object_list #QuerySet只有8条数据
2,for item in curr_pg_obj:
  print(item)

-----------template模板-----------
循环页码:页数paginator.num_pages
循环内容:当前页对象curr_pg_obj

for pg in pages:
  if pg=curr_pg
  print(选中的pg)
else
  print(pg)

--------------------------------------

# curr_pg_obj.has_next() 是否有下一页
# curr_pg_obj.next_page_number() 下一页页码
# curr_pg_obj.has_previous() 是否有上一页
# curr_pg_obj.previous_page_number() 上一页的页码

# 抛错
#page=paginator.page(99) # error:EmptyPage
#page=paginator.page("z") # error:PageNotAnInteger

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" 
    integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>

<div class="container">

    <h4>分页器</h4>
    <ul>

        {% for book in curr_pg_obj %}
             <li>{{ book.title }} -----{{ book.price }}</li>
        {% endfor %}

     </ul>


    <ul class="pagination" id="pager">

                 {% if curr_pg_obj.has_previous %}
                    <li class="previous"><a href="/index/?page={{ curr_pg_obj.previous_page_number }}">上一页</a></li>
                 {% else %}
                    <li class="previous disabled"><a href="#">上一页</a></li>
                 {% endif %}


                 {% for num in paginator.page_range %}

                     {% if num == currentPage %}
                       <li class="item active"><a href="/index/?page={{ num }}">{{ num }}</a></li>
                     {% else %}
                       <li class="item"><a href="/index/?page={{ num }}">{{ num }}</a></li>

                     {% endif %}
                 {% endfor %}



                 {% if curr_pg_obj.has_next %}
                    <li class="next"><a href="/index/?page={{ curr_pg_obj.next_page_number }}">下一页</a></li>
                 {% else %}
                    <li class="next disabled"><a href="#">下一页</a></li>
                 {% endif %}

            </ul>
</div>



</body>
</html>

 

posted on 2019-04-19 02:00  要一直走下去  阅读(147)  评论(0编辑  收藏  举报