Django实现分页
views.py
中
from django.core.paginator import Paginator
from django.shortcuts import render
from .models import Blog,BlogType
def blog_list(request):
# 获取所有博客
blog_all_list = Blog.objects.all()
# 每10页进行分页
paginator = Paginator(blog_all_list,10)
page_num = request.GET.get('page',1) # 获取url的页面参数
# 根据页码获取每页数据 页码参数出错时,自动转为第一页
page_of_blogs = paginator.get_page(page_num)
currenter_num = page_of_blogs.number # 获取当前页码
# 获取当前页码前后各2页的页码范围
page_range = list(range(max(currenter_num-2,1),currenter_num))+list(range(currenter_num,min(currenter_num+2,paginator.num_pages)+1))
# 加上省略页码标记
if page_range[0] -1 >=2:
page_range.insert(0,'...')
if paginator.num_pages - page_range[-1] >=2:
page_range.append('...')
# 加上首页和尾页
if page_range[0] !=1:
page_range.insert(0,1)
if page_range[-1] != paginator.num_pages:
page_range.append(paginator.num_pages)
blog_type_list = BlogType.objects.all()
return render(request,'blog/blog_list.html',locals())
前端blog/blog_list.html
中,借助于bootstrap
{% block heading_title %}博客列表{% endblock %}
{% for blog in page_of_blogs.object_list %}
{{ blog.title }}
{{ blog.blog_type }}
发表日期:{{ blog.create_time|date:'Y-m-d H:i:s' }}
{{ blog.content|truncatechars:30 }}
{% empty %}
暂无博客,敬请更新
{% endfor %}
一共有篇{{ blog_all_list|length }}博客,当前是{{ page_of_blogs.number }}页,一共有{{ page_of_blogs.paginator.num_pages }}页