分页和shell命令行模式
1、为什么要先讲分页功能
2、快速添加博客
for i in range(1,31):
...: blog = Blog()
...: blog.title = "for %s" % i
...: blog.content = "xxxx:%s" % i
...: blog.blog_type = blog_type
...: blog.author = user
...: blog.save()
Blog.objects.all().count()
34
3、模型新增对象
4、分页器实现分页
那么文章多了需要分页
现在models.py中进行排序处理(最新发表文章排在前面)
class Meta:
ordering = ['-created_time']
接下来要迁移文件操作
python manage.py makemigrations
python manage.py migrate
迁移完成后要先退出shell
# 先退出,再启动
exit()
python manage.py shell
# 引入分页器
from django.core.paginator import Paginator
# 引入Blog模型
from blog.models import Blog
# 拿到全部的Blog
blogs = Blog.objects.all()
# 再给这些blog进行分页,每页十个
paginator = Paginator(blogs,10)
查看一下
In [5]: paginator.count
Out[5]: 34
In [6]: paginator.num_pages
Out[6]: 4
In [7]: paginator.page_range
Out[7]: range(1, 5)
In [8]: page1 = paginator.page(1)
In [10]: page1
Out[10]: <Page 1 of 4> # 表示4页中的第1页
5、分页的使用
在views.py中修改
def blog_list(request):
blogs_all_list = Blog.objects.all()
paginator = Paginator(blogs_all_list,10) # 每10页进行分页
page_num = request.GET.get('page', 1) # 获取url的页面参数
page_of_blogs = paginator.get_page(page_num)
context = {}
context['page_of_blogs'] = page_of_blogs
context['blog_types'] = BlogType.objects.all()
return render_to_response('blog/blog_list.html', context)
修改blog_list.html
<div class="panel-heading">{% block blog_list_title %}博客列表(一共有{{ page_of_blogs.paginator.count|length }}篇博客){% endblock %}</div>
<div class="panel-body">
{% for blog in page_of_blogs.object_list %}
http://127.0.0.1:8000/blog/?page=
修改页码样式(https://v3.bootcss.com/components/#pagination)
blog_list.html
<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_of_blogs.paginator.page_range %}
<li><a href="?page={{ page_num }}">{{ page_num }}</a></li>
{% 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>