django 實現分頁功能


分頁效果:

視圖代碼:

 1 # -*- coding: utf-8 -*-
 2 from django.shortcuts import render,get_object_or_404
 3 from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage  
 4 
 5 from .models import Article
 6 
 7 # Create your views here.
 8 
 9 def index(request):
10     # latest_article_list = Article.objects.order_by('update')[:5]
11     # context = {'latest_article_list':  latest_article_list}
12     # return render(request, 'blog/index.html',context)
13     article_list = Article.objects.all().order_by('cre_date') 
14     paginator = Paginator(article_list,2) #show 2 articles per page
15 
16     page = request.GET.get('page')
17 
18     try:
19         articles = paginator.page(page)
20     except PageNotAnInteger:
21         #頁碼不是整數,返回第一頁。
22         articles = paginator.page(1)
23     except EmptyPage:
24         articles = paginator.page(paginator.num_pages)
25 
26     return render(request, 'blog/index.html', {'articles': articles})

paginator是分頁實例,page是鏈接傳遞到后端的頁碼參數,articles是每頁的實例。

在次例中,paginator是把所有文章(article_list)按照每頁兩個划分,划成3頁。page是前端請求的頁碼。articles是根據請求頁碼返回的具體的該頁碼內的文章(2篇文章)。

paginator和articles的屬性和方法詳見文檔:https://docs.djangoproject.com/en/1.8/topics/pagination/

 

前端代碼:

 1 <!--分頁-->
 2 <nav>
 3   <div class="pagination pagination-right">
 4     <ul >
 5     <li>
 6         {% if articles.has_previous %}
 7             <a href="?page={{ articles.previous_page_number }}" class="active">&laquo;</a>
 8         {% endif %}
 9         {% if not articles.has_previous %}
10             <a href="" >&laquo;</a>
11         {% endif %}
12     </li>
13 
14     <li>
15         {% for i in articles.paginator.page_range %}
16             <li {% if articles.number == i %}class="active"{% endif %}>
17                 <a  href="?page={{ i }}">{{ i }}
18 
19                 </a>
20         </li>
21         {% endfor %}
22     </li>
23 
24     <li>
25         {% if articles.has_next %}
26             <a href="?page={{ articles.next_page_number }}" >&raquo;</a>
27         {% endif %}
28         {% if not articles.has_next %}
29             <a href="" >&raquo;</a>
30         {% endif %}
31     </li>
32 
33     <li>
34         共{{ articles.paginator.num_pages }}頁
35     </li>
36     </ul>
37     </div>
38 </nav>
39 <!--ending 分頁-->

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM