1. 程式人生 > 程式設計 >如何在django中實現分頁功能

如何在django中實現分頁功能

1.在html頁面中匯入js檔案和css檔案

<link rel="stylesheet" href="../../../static/css/jquery.pagination.css" rel="external nofollow" >
<script type="text/javascript" src="../../../static/js/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="../../../static/js/jquery.pagination.min.js"></script>

2.寫一個展示分頁的div容器

<div id="pagination" class="page"></div>

3.前端分頁邏輯

<script>
  $(function(){
    $("#pagination").pagination({
      currentPage:{{current_page}},totalPage:{{total_page}},callback:function(current){
      window.location.href = '?page='+current
        }
     });
});
</script>

4.django獲取當前頁數,定義每頁展示的數量,和返回資料等

from django.core.paginator import Paginator
def detail(request,id):
  category = models.Category.objects.all()
  news = models.News.objects.filter(cate=id).all()
  # 從url上獲取當前請求的頁數
  p = request.GET.get('page',1)
  current_page = int(p)
  # 每頁顯示的條數
  page_count = 1
  # 顯示資料庫資料,並且規定每頁顯示多少條資料
  page = Paginator(news,page_count)
  # 當前請求的頁數
  news = page.get_page(current_page)
  # 顯示的總頁數
  total_page = page.num_pages
return render(request,'app1/news.html',locals())

django中的分頁功能已經完成,效果圖如下:

如何在django中實現分頁功能

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。