搭建自己的博客(十四):简单的为博客添加阅读量

强颜欢笑 提交于 2020-03-01 09:31:16

1、变化的部分

2、上代码

ul.blog-types,ul.blog-dates {
    list-style-type: none;
}

div.blog:not(:last-child) {
    margin-bottom: 2em;
    padding-bottom: 1em;
    border-bottom: 1px solid #eee;
}

div.blog h3 {
    margin-top: 0.5em;
}

div.blog-info p {
    margin-bottom: 0;
}
div.blog-info p span{
    margin-right: 10px;
}

div.blog-info-description {
    list-style-type: none;
    margin-bottom: 1em;
}

ul.blog-info-description li {
    display: inline-block;
    margin-right: 1em;
}

div.paginator {
    text-align: center;
}

div.container {
    max-width: 80%;
}
blog.css
{# 引用模板 #}
{% extends 'base.html' %}

{% load staticfiles %}
{% block header_extends %}
    <link rel="stylesheet" href="{% static 'blog/blog.css' %}">
{% endblock %}


{# 标题 #}
{% block title %}
    {{ blog.title }}
{% endblock %}

{# 内容#}
{% block content %}
    <div class="container">
        <div class="row">
            <div class="col-6 offset-1">
                <ul class="blog-info-description">
                    <h3>{{ blog.title }}</h3>
                    <li>作者:{{ blog.author }}</li>
                    {# 时间过滤器让时间按照自己需要的格式过滤 #}
                    <li>发布日期:{{ blog.created_time|date:"Y-m-d H:n:s" }}</li>
                    <li>分类:
                        <a href="{% url 'blogs_with_type' blog.blog_type.pk %}">
                            {{ blog.blog_type }}
                        </a>
                    </li>
                    <li>阅读({{ blog.read_num }})</li>
                </ul>
                <p class="blog-content">{{ blog.content|safe }}</p>


                <p>上一篇:
                    {% if previous_blog %}
                       <a href="{% url 'blog_detail' previous_blog.pk %}">{{ previous_blog.title }}</a>
                    {% else %}
                        <span>没有了</span>
                    {% endif %}
                </p>
                <p>下一篇:
                    {% if next_blog %}
                        <a href="{% url 'blog_detail' next_blog.pk %}">{{ next_blog.title }}</a>
                    {% else %}
                        <span>没有了</span>
                    {% endif %}
                </p>
            </div>
        </div>
    </div>


{% endblock %}

{% block js %}
    <script>
        $(".nav-blog").addClass("active").siblings().removeClass("active");
    </script>
{% endblock %}
blog_detail.html
{% 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 %}博客列表{% endblock %}</h5>
                    </div>
                    <div class="card-body">
                        {% for blog in blogs %}
                            <div class="blog">
                                <h3><a href="{% url 'blog_detail' blog.pk %}">{{ blog.title }}</a></h3>
                                <div class="blog-info">
                                    <p>
                                        {# 添加图标 #}
                                        <span>
                                            <i class="fas fa-tag"></i>
                                            <a href="{% url 'blogs_with_type' blog.blog_type.pk %}">
                                                {{ blog.blog_type }}
                                            </a>
                                        </span>
                                        <span>
                                            <i class="far fa-clock  "></i>
                                            {{ blog.created_time|date:"Y-m-d" }}
                                        </span>
                                        <span>阅读({{ blog.read_num }})</span>

                                    <p>
                                </div>
                                <p>{{ blog.content|safe|truncatechars:30 }}</p>
                            </div>
                        {% empty %}
                            <div class="blog">
                                <h3>--暂无博客,敬请期待--</h3>
                            </div>
                        {% endfor %}
                    </div>
                </div>

                {# 分页 #}
                <div class="paginator">
                    <ul class="pagination justify-content-center">
                        {# 首页 #}
                        <li class="page-item"><a class="page-link" href="?page=1">首页</a></li>
                        {# 上一页 #}
                        {% 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"><span class="page-link">上一页</span></li>
                        {% endif %}
                        {# 全部页码 #}
                        {% for page_num in page_range %}
                            {# 添加当前页高亮显示 #}
                            {% if page_num == page_of_blogs.number %}
                                <li class="page-item active"><span class="page-link">{{ page_num }}</span></li>
                            {% else %}
                                <li class="page-item"><a class="page-link"
                                                         href="?page={{ page_num }}">{{ page_num }}</a></li>
                            {% endif %}
                        {% 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"><span class="page-link">下一页</span></li>
                        {% endif %}
                        {# 尾页 #}
                        <li class="page-item"><a class="page-link"
                                                 href="?page={{ page_of_blogs.paginator.num_pages }}">尾页</a></li>
                    </ul>

                    <p>
                        一共有 {{ page_of_blogs.paginator.count }}篇博客,当前{{ page_of_blogs.number }}页,共{{ page_of_blogs.paginator.num_pages }}页
                    </p>

                </div>
            </div>

            <div class="col-md-4">
                <div class="card">
                    <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 }}({{ blog_type.blog_count }})</a>
                                </li>
                            {% empty %}
                                <li>暂无分类</li>
                            {% endfor %}
                        </ul>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header"><h5 class="card-title">日期归档</h5></div>
                    <div class="card-body">
                        <ul class="blog-dates">
                            {% for blog_date,blog_count in blog_dates.items %}
                                <li>
                                    <a href="{% url 'blogs_with_date' blog_date.year blog_date.month %}">
                                        {{ blog_date|date:'Y年m月' }}({{ blog_count }})
                                    </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 %}
blog_list.html
from django.contrib import admin
from .models import BlogType, Blog


# Register your models here.

@admin.register(BlogType)
class BlogTypeAdmin(admin.ModelAdmin):
    list_display = ('id', 'type_name')  # 需要显示的列表


@admin.register(Blog)
class BlogAdmin(admin.ModelAdmin):
    list_display = ('title', 'blog_type', 'author','read_num', 'created_time', 'last_updated_time')

# 上面的装饰器和这句相同
# admin.site.register(Blog,BlogAdmin)
admin.py
from django.db import models
from django.contrib.auth.models import User
from ckeditor_uploader.fields import RichTextUploadingField


# 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 = RichTextUploadingField()  # 博客内容,使用富文本编辑
    author = models.ForeignKey(User, on_delete=models.DO_NOTHING)  # 博客作者
    read_num=models.IntegerField(default=0)
    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']  # 定义排序规则,按照创建时间倒序
models.py
from django.shortcuts import render_to_response, get_object_or_404
from .models import Blog, BlogType
from django.core.paginator import Paginator
from django.conf import settings
from django.db.models import Count


# 分页部分公共代码
def blog_list_common_data(requests, blogs_all_list):
    paginator = Paginator(blogs_all_list, settings.EACH_PAGE_BLOGS_NUMBER)  # 第一个参数是全部内容,第二个是每页多少
    page_num = requests.GET.get('page', 1)  # 获取url的页面参数(get请求)
    page_of_blogs = paginator.get_page(page_num)  # 从分页器中获取指定页码的内容

    current_page_num = page_of_blogs.number  # 获取当前页
    all_pages = paginator.num_pages
    if all_pages < 5:
        page_range = list(
            range(max(current_page_num - 2, 1),
                  min(all_pages + 1, current_page_num + 3)))  # 获取需要显示的页码 并且剔除不符合条件的页码
    else:
        if current_page_num <= 2:
            page_range = range(1, 5 + 1)
        elif current_page_num >= all_pages - 2:
            page_range = range(all_pages - 4, paginator.num_pages + 1)
        else:
            page_range = list(
                range(max(current_page_num - 2, 1),
                      min(all_pages + 1, current_page_num + 3)))  # 获取需要显示的页码 并且剔除不符合条件的页码

    blog_dates = Blog.objects.dates('created_time', 'month', order='DESC')
    blog_dates_dict = {}
    for blog_date in blog_dates:
        blog_count = Blog.objects.filter(created_time__year=blog_date.year, created_time__month=blog_date.month).count()
        blog_dates_dict = {
            blog_date: blog_count
        }

    return {
        'blogs': page_of_blogs.object_list,
        'page_of_blogs': page_of_blogs,
        'blog_types': BlogType.objects.annotate(blog_count=Count('blog')),  # 添加查询并添加字段
        'page_range': page_range,
        'blog_dates': blog_dates_dict
    }


# 博客列表
def blog_list(requests):
    blogs_all_list = Blog.objects.all()  # 获取全部博客
    context = blog_list_common_data(requests, blogs_all_list)
    return render_to_response('blog/blog_list.html', context)


# 根据类型筛选
def blogs_with_type(requests, blog_type_pk):
    blog_type = get_object_or_404(BlogType, pk=blog_type_pk)
    blogs_all_list = Blog.objects.filter(blog_type=blog_type)  # 获取全部博客
    context = blog_list_common_data(requests, blogs_all_list)
    context['blog_type'] = blog_type
    return render_to_response('blog/blog_with_type.html', context)


# 根据日期筛选
def blogs_with_date(requests, year, month):
    blogs_all_list = Blog.objects.filter(created_time__year=year, created_time__month=month)  # 获取全部博客
    context = blog_list_common_data(requests, blogs_all_list)
    context['blogs_with_date'] = '{}年{}日'.format(year, month)
    return render_to_response('blog/blog_with_date.html', context)


# 博客详情
def blog_detail(requests, blog_pk):
    blog = get_object_or_404(Blog, pk=blog_pk)
    if not requests.COOKIES.get('blog_{}_read'.format(blog_pk)):
        # 处理阅读量
        blog.read_num += 1
        blog.save()

    context = {
        'blog': blog,
        'previous_blog': Blog.objects.filter(created_time__gt=blog.created_time).last(),
        'next_blog': Blog.objects.filter(created_time__lt=blog.created_time).first(),
    }
    response=render_to_response('blog/blog_detail.html', context)
    response.set_cookie('blog_{}_read'.format(blog_pk),'true')

    return response
views.py

3、当然这种方法有很多需要优化的地方,这种方法改动了阅读量,就会带动数据库中的其他字段跟着改变。下篇博客继续优化。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!