搭建自己的博客(九):使用shell模式批量添加博客文章并增加分页功能
想做个博客分页功能,但是没有太多的文章。所以使用shell命令行创建多篇文章。
1、打开pycharm下的terminal终端
python manage.py shell # 打开python终端
导入模型
from blog.models import Blog from django.contrib.auth.models import User from blog.models import BlogType
批量创建:
>>> blog.author=user >>> blog.blog_type=blogtype >>> blog.content="shell第一篇中的内容" >>> blog.save() >>> for i in range(1,51): ... blog=Blog() ... blog.author=user ... blog.blog_type=blogtype ... blog.content="shell 下第{}篇内容".format(i) ... blog.title="shell 下第{}篇".format(i) ... blog.save()
这样就批量创建了50篇内容。
内容多了就需要添加分页的功能。
1、变更的内容
2、上代码
{% extends 'base.html' %} {% load staticfiles %} {# 标题 #} {% block title %} felix Blog {% endblock %} {% block header_extends %} <link rel="stylesheet" href="{% static 'blog/blog.css' %}"> <link rel="stylesheet" href="{% static 'fontawesome-free-5.5.0-web/css/all.min.css' %}"> {% endblock %} {# 内容#} {% block content %} <div class="container"> <div class="row"> <div class="col-md-8"> <div class="card" style=""> <div class="card-header"><h5 class="card-title">{% block blog_type_title %}博客列表(一共有 {{ page_of_blogs.paginator.count }}篇博客){% endblock %}</h5></div> <div class="card-body"> {% for blog in page_of_blogs.object_list %} <div class="blog"> <h3><a href="{% url 'blog_detail' blog.pk %}">{{ blog.title }}</a></h3> <div class="blog-info"> <p> {# 添加图标 #} <i class="fas fa-tag"></i> <a href="{% url 'blogs_with_type' blog.blog_type.pk %}"> {{ blog.blog_type }} </a> <i class="far fa-clock "></i> {{ blog.created_time|date:"Y-m-d" }} <p> </div> <p>{{ blog.content|truncatechars:30 }}</p> </div> {% empty %} <div class="blog"> <h3>--暂无博客,敬请期待--</h3> </div> {% endfor %} </div> {# 分页 #} <nav aria-label="Page navigation"> <ul class="pagination"> {# 上一页 #} {% if page_of_blogs.has_previous %} <li class="page-item"><a class="page-link" href="?page={{ page_of_blogs.previous_page_number }}">上一页</a> </li> {% else %} <li class="page-item disabled"><a class="page-link" href="#">上一页</a></li> {% endif %} {# 全部页码 #} {% for page_num in page_of_blogs.paginator.page_range %} <li class="page-item"><a class="page-link" href="?page={{ page_num }}">{{ page_num }}</a></li> {% endfor %} {# 下一页 #} {% if page_of_blogs.has_next %} <li class="page-item"><a class="page-link" href="?page={{ page_of_blogs.next_page_number }}">下一页</a></li> {% else %} <li class="page-item disabled"><a class="page-link" href="#">下一页</a></li> {% endif %} </ul> </nav> </div> </div> <div class="col-md-4"> <div class="card" style=""> <div class="card-header"><h5 class="card-title">博客分类</h5></div> <div class="card-body"> <ul class="blog-types"> {% for blog_type in blog_types %} <li><a href="{% url 'blogs_with_type' blog_type.pk %}">{{ blog_type.type_name }}</a> </li> {% empty %} <li>暂无分类</li> {% endfor %} </ul> </div> </div> </div> </div> </div> {% endblock %} {% block js %} <script> $(".nav-blog").addClass("active").siblings().removeClass("active"); </script> {% endblock %}
from django.db import models from django.contrib.auth.models import User # Create your models here. # 博客分类 class BlogType(models.Model): type_name = models.CharField(max_length=15) # 博客分类名称 def __str__(self): # 显示标签名 return self.type_name # 博客 class Blog(models.Model): title = models.CharField(max_length=50) # 博客标题 blog_type = models.ForeignKey(BlogType, on_delete=models.DO_NOTHING) # 博客分类 content = models.TextField() # 博客内容 author = models.ForeignKey(User, on_delete=models.DO_NOTHING) # 博客作者 created_time = models.DateTimeField(auto_now_add=True) # 博客创建时间 last_updated_time = models.DateTimeField(auto_now=True) # 博客更新事件 def __str__(self): # 显示标题名 return "<Blog:{}>".format(self.title) class Meta: ordering = ['-created_time'] # 定义排序规则,按照创建时间倒序
from django.shortcuts import render_to_response, get_object_or_404 from .models import Blog, BlogType from django.core.paginator import Paginator # Create your views here. # 博客列表 def blog_list(requests): # 分页 blogs_all_list = Blog.objects.all() # 获取全部博客 paginator = Paginator(blogs_all_list, 10) # 第一个参数是全部内容,第二个是每页多少 page_num = requests.GET.get('page', 1) # 获取url的页面参数(get请求) page_of_blogs = paginator.get_page(page_num) # 从分页器中获取指定页码的内容 context = { 'page_of_blogs': page_of_blogs, 'blog_types': BlogType.objects.all(), } return render_to_response('blog/blog_list.html', context) # 博客详情 def blog_detail(requests, blog_pk): context = { 'blog': get_object_or_404(Blog, pk=blog_pk) } return render_to_response('blog/blog_detail.html', context) def blogs_with_type(requests, blog_type_pk): blog_type = get_object_or_404(BlogType, pk=blog_type_pk) context = { 'blogs': Blog.objects.filter(blog_type=blog_type), 'blog_type': blog_type, 'blog_types': BlogType.objects.all(), } return render_to_response('blog/blog_with_type.html', context)
3、python内置分页器
django的内置分页器为Paginator
用法:
>>> from blog.models import Blog >>> from django.core.paginator import Paginator >>> paginator=Paginator(Blog.objects.all(),10) >>> pages=paginator.get_page(1) >>> dir(pages) ['__abstractmethods__', '__class__', '__contains__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_abc_cache', '_abc_negative_cache', '_abc_negative_cache_version', '_abc_registry', 'count', 'end_index', 'has_next', 'has_other_pages', 'has_previous', 'index', 'next_page_number', 'number', 'object_list', 'paginator', 'previous_page_number', 'start_index'] >>>
从dir(pages)可以看到很多属性和方法。
比如说:
count 个数
has_next 是否有下一页
has_previous 是否有上一页
next_page_number 下一页的页码
previous_page_number 上一页的页码