码迷,mamicode.com
首页 > 其他好文 > 详细

Django的分页

时间:2018-10-30 19:29:16      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:sha   get   服务   charset   bsp   meta   end   create   list   

1.插入批量数据

    book_list = []
    for i in range(1,101):
        book = Book(title="book_%s"%i,price=i*i)
        book_list.append(book)
    Book.objects.bulk_create(book_list)

2.分页器的使用

    book_list = Book.objects.all()
    print(book_list)
    paginator = Paginator(book_list, 10)
    print(paginator.count)  #对象总数
    print(paginator.num_pages)  #分页数
    print(paginator.page_range) #range(1,11)
    page = paginator.page(5)    #第几页的数据
    for i in page:
        print(i)
    print(page.has_next())  #是否有下一页  True
    print(page.has_previous()) #是否有上一页
    print(page.next_page_number()) #下一页是第几页
    print(page.previous_page_number())  #上一页是第几页

3.服务器端

def index(request):
    book_list = Book.objects.all()
    paginator = Paginator(book_list,10)
    current_page_num = request.GET.get("page",1)
    current_page = paginator.page(current_page_num)
    return render(request,"index.html",{"current_page":current_page,"paginator":paginator,"current_page_num":int(current_page_num)})

4.前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
     <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<ul>
    {% for book in current_page %}
        <li>{{ book.title }}------{{ book.price }}</li>
    {% endfor %}
    
</ul>
<nav aria-label="Page navigation">
  <ul class="pagination">
    {% if current_page.has_previous %}
        <li><a href="?page={{ current_page.previous_page_number }}" aria-label="Previous"><span aria-hidden="true">上一页</span></a></li>
     {% else %}
        <li class="disabled"><a href="">上一页</a></li>
    {% endif %}
      {% for i in paginator.page_range %}
          {% if current_page_num == i %}
             <li class="active"><a href="?page={{ i }}">{{ i }}</a></li>
          {% else %}
              <li><a href="?page={{ i }}">{{ i }}</a></li>
          {% endif %}
      {% endfor %}
    {% if current_page.has_next%}
        <li>
          <a href="?page={{ current_page.next_page_number }}" aria-label="Next">
            <span aria-hidden="true">下一页</span>
          </a>
        </li>
     {% else %}
        <li class="disabled"><a href="">下一页</a></li>
    {% endif %}

  </ul>
</nav>
</body>
</html>

 

Django的分页

标签:sha   get   服务   charset   bsp   meta   end   create   list   

原文地址:https://www.cnblogs.com/qq849784670/p/9878779.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!