您的位置:首页 > 编程语言 > Go语言

django 实现分页功能

2016-04-23 20:41 579 查看
分页效果:



视图代码:

# -*- coding: utf-8 -*-
from django.shortcuts import render,get_object_or_404
from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage

from .models import Article

# Create your views here.

def index(request):
# latest_article_list = Article.objects.order_by('update')[:5]
# context = {'latest_article_list':  latest_article_list}
# return render(request, 'blog/index.html',context)
article_list = Article.objects.all().order_by('cre_date')
paginator = Paginator(article_list,2) #show 2 articles per page

page = request.GET.get('page')

try:
articles = paginator.page(page)
except PageNotAnInteger:
#页码不是整数,返回第一页。
articles = paginator.page(1)
except EmptyPage:
articles = paginator.page(paginator.num_pages)

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/

前端代码:

<!--分页-->
<nav>
<div class="pagination pagination-right">
<ul >
<li>
{% if articles.has_previous %}
<a href="?page={{ articles.previous_page_number }}" class="active">«</a>
{% endif %}
{% if not articles.has_previous %}
<a href="" >«</a>
{% endif %}
</li>

<li>
{% for i in articles.paginator.page_range %}
<li {% if articles.number == i %}class="active"{% endif %}>
<a  href="?page={{ i }}">{{ i }}

</a>
</li>
{% endfor %}
</li>

<li>
{% if articles.has_next %}
<a href="?page={{ articles.next_page_number }}" >»</a>
{% endif %}
{% if not articles.has_next %}
<a href="" >»</a>
{% endif %}
</li>

<li>
共{{ articles.paginator.num_pages }}页
</li>
</ul>
</div>
</nav>
<!--ending 分页-->
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: