博客五部曲之一 - 简单博客
1397 浏览 5 years, 11 months
27 分页
版权声明: 转载请注明出处 http://www.codingsoho.com/发布博客多了之后,列表会过长,这时候我们需要引入分页来优化内容的加载和查看。
根据官方手册一步步操作就行了
https://docs.djangoproject.com/en/1.11/topics/pagination/#using-paginator-in-a-view
首先,在view里添加处理函数
def post_list(request):
queryset_list = Post.objects.all()
paginator = Paginator(queryset_list, 2)
page_var = 'page'
page = request.GET.get(page_var)
try:
queryset = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
queryset = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
queryset = paginator.page(paginator.num_pages)
context = {
'object_list': queryset,
'title': 'List',
'page_var' : page_var,
}
return render(request, "post_list.html",context)
Paginator类的第一个参数是QuerySet,第二个参数为在一页上显示的条目个数
Page_var用于GET里指示page的参数,这儿用参数让他灵活化了。
<div class="pagination">
<span class="step-links">
{% if object_list.has_previous %}
<a href="?{{page_var}}={{ object_list.previous_page_number }}">previous</a>
{% endif %}
<span class="current">
Page {{ object_list.number }} of {{ object_list.paginator.num_pages }}.
</span>
{% if object_list.has_next %}
<a href="?{{page_var}}={{ object_list.next_page_number }}">next</a>
{% endif %}
</span>
</div>
在page_list里添加上面的代码用于页面导航, object_list是Post的QuerySet