分页效果:
视图代码:
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">«</a>
8 {% endif %}
9 {% if not articles.has_previous %}
10 <a href="" >«</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 }}" >»</a>
27 {% endif %}
28 {% if not articles.has_next %}
29 <a href="" >»</a>
30 {% endif %}
31 </li>
32
33 <li>
34 共{{ articles.paginator.num_pages }}页
35 </li>
36 </ul>
37 </div>
38 </nav>
39 <!--ending 分页-->