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
<div class="col-sm-8">
<div class="panel panel-primary">
<div class="panel-heading">{% block heading_title %}博客列表{% endblock %}</div>
<div class="panel-body">
{% for blog in page_of_blogs.object_list %}
<a href="{% url 'blog:blog_detail' blog.id %}"><h3>{{ blog.title }}</h3></a>
<p>
<span class="glyphicon glyphicon-tag"></span>
<a href="{% url 'blog:blog_with_type' blog.blog_type.pk %}">{{ blog.blog_type }}</a>
<span class="glyphicon glyphicon-time"></span>
发表日期:{{ blog.create_time|date:'Y-m-d H:i:s' }}
</p>
<p>{{ blog.content|truncatechars:30 }}</p>
<hr>
{% empty %}
<p>暂无博客,敬请更新</p>
{% endfor %}
</div>
</div>
<nav aria-label="Page navigation">
<ul class="pagination">
{# 上一页 #}
<li>
{% if page_of_blogs.has_previous %}
<a href="?page={{ page_of_blogs.previous_page_number }}" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
{% else %}
<span aria-hidden="true">«</span>
{% endif %}
</li>
{# 页码 #}
{% for page_num in page_range %}
{# 当前页高亮 #}
{% if page_num == page_of_blogs.number %}
<li class="active"><a href="?page={{ page_num }}">{{ page_num }}</a></li>
{% else %}
{# 省略页码 #}
{% if page_num == '...' %}
<li><a href="#">{{ page_num }}</a></li>
{% else %}
<li><a href="?page={{ page_num }}">{{ page_num }}</a></li>
{% endif %}
{% endif %}
{% endfor %}
{# 下一页 #}
<li>
{% if page_of_blogs.has_next %}
<a href="?page={{ page_of_blogs.next_page_number }}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
{% else %}
<span aria-hidden="true">»</span>
{% endif %}
</li>
</ul>
</nav>
<p> 一共有篇{{ blog_all_list|length }}博客,当前是{{ page_of_blogs.number }}页,一共有{{ page_of_blogs.paginator.num_pages }}页</p>
</div>
网友评论