十七、Django2.1 搭建多用户的博客网站——统计文章浏览次数

1字数 920阅读 451

目录:Django 2.1 从零开始搭建博客网站系列

服务器环境搭建(选学)

小试牛刀——简单的博客网站

庖丁解牛——多用户的博客网站之用户模块

庖丁解牛——多用户的博客网站之文章模块

华丽转身——多用户的博客网站之扩展功能

项目源码下载:https://github.com/jt1024/lehehe

正文:

1、安装Redis

安装:在Mac环境下,执行 brew install redis 命令,可安装Redis。
启动:安装成功后,执行 redis-server /usr/local/etc/redis.conf 命令,可启动Redis。启动成功会显示如图:


启动Redis成功

客户端:启动Redis后,再打开一个命令终端,执行 redis-cli 可以进入 Redis 客户端,成功进入后如图


进入 Redis 客户端

Windows环境可百度自行查阅,推荐参考 http://www.runoob.com/redis/redis-install.html

2、在Python中使用Redis

执行命令 pip install redis 可安装Python的Redis库。

3、记录阅读次数

在 ./lehehe/settings.py 文件中做好数据库的配置,即在最后增加如下变量

# Redis配置
REDIS_HOST = 'localhost'
REDIS_PORT = 6379
REDIS_DB = 0

修改 ./article/list_views.py 建立与 Redis 数据库的连接,即新增如下代码

import redis
from django.conf import settings

r = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB)

修改 ./article/list_views.py 中的 article_detail 方法

def article_detail(request, id, slug):
    article = get_object_or_404(ArticlePost, id=id, slug=slug)
    total_views = r.incr("article:{}:views".format(article.id))
    return render(request, "article/list/article_content.html", {"article": article, "total_views": total_views})

修改 ./templates/article/list/article_content.html 在这行代码

<span style="margin-left:20px" class="glyphicon glyphicon-thumbs-up">{{ total_likes }}like{{ total_likes|pluralize }}</span>

后新增如下代码

<span style="margin-left:20px">{{ total_views }} view{{ total_views|pluralize}}</span>

打开文章详情,刷新页面,查看效果。

4、显示最热文章

修改 ./article/list_views.py 中的 article_detail 方法

def article_detail(request, id, slug):
    article = get_object_or_404(ArticlePost, id=id, slug=slug)
    total_views = r.incr("article:{}:views".format(article.id))
    r.zincrby('article_ranking', 1, article.id)

    article_ranking = r.zrange("article_ranking", 0, -1, desc=True)[:10]
    article_ranking_ids = [int(id) for id in article_ranking]
    most_viewed = list(ArticlePost.objects.filter(id__in=article_ranking_ids))
    most_viewed.sort(key=lambda x: article_ranking_ids.index(x.id))
    return render(request, "article/list/article_content.html", {"article": article, "total_views": total_views, "most_viewed": most_viewed})

修改 ./templates/article/list/article_content.html 增加如下代码

<div class="col-md-3">
        <p class="text-center">
        <h3>最受欢迎文章</h3></p>
        <ol>
            {% for article_rank in most_viewed %}
            <li>
                <a href="{{article_rank.get_url_path}}">{{ article_rank.title }}</a>
            </li>
            {% endfor %}
        </ol>
    </div>

修改后的完整代码如下

{% extends "base.html" %}
{% load staticfiles %}
{% block title %}articles list{% endblock %}
{% block content %}

{% with total_likes=article.users_like.count users_like=article.users_like.all %}
<div class="container">
    <div class="col-md-9">
        <header>
            <h1>{{ article.title }}</h1>
            <p>
                <a href="{% url 'article:author_articles' article.author.username %}">{{ article.author.username }}</a>
                <span style="margin-left:20px" class="glyphicon glyphicon-thumbs-up">{{ total_likes }}like{{ total_likes|pluralize }}</span>
                <span style="margin-left:20px">{{ total_views }} view{{ total_views|pluralize}}</span>
            </p>
        </header>

        <link rel="stylesheet" href="{% static 'editor/css/editormd.preview.css' %}"/>
        <div id='editormd-view'>
        <textarea id="append-test" style="display:none;">
{{ article.body }}
        </textarea>
        </div>
        <div>
            <p class="text-center">
                <a onclick="like_article({{article.id}}, 'like')" href="#">
                    <span class="glyphicon glyphicon-thumbs-up">like</span>
                </a>
                <a onclick="like_article({{article.id}}, 'unlike')" href="#">
                    <span style="margin-left: 15px;" class="glyphicon glyphicon-thumbs-down">unlike</span>
                </a>
            </p>
        </div>
        <div>
            <p class="text-center"><strong>点赞本文的读者</strong></p>
            {% for user in article.users_like.all %}
            <p class="text-center">{{user.username}}</p>
            {% empty %}
            <p class="text-center">还没有人对此文章表态</p>
            {% endfor %}
        </div>
    </div>
    <div class="col-md-3">
        <p class="text-center">
        <h3>最受欢迎文章</h3></p>
        <ol>
            {% for article_rank in most_viewed %}
            <li>
                <a href="{{article_rank.get_url_path}}">{{ article_rank.title }}</a>
            </li>
            {% endfor %}
        </ol>
    </div>
</div>

<script src='{% static "js/jquery.js" %}'></script>
<script src='{% static "editor/lib/marked.min.js" %}'></script>
<script src='{% static "editor/lib/prettify.min.js" %}'></script>
<script src='{% static "editor/lib/raphael.min.js" %}'></script>
<script src='{% static "editor/lib/underscore.min.js" %}'></script>
<script src='{% static "editor/lib/sequence-diagram.min.js" %}'></script>
<script src='{% static "editor/lib/flowchart.min.js" %}'></script>
<script src='{% static "editor/lib/jquery.flowchart.min.js" %}'></script>
<script src='{% static "editor/editormd.js" %}'></script>
<script type="text/javascript" src="{% static 'js/layer.js'%}"></script>
<script type="text/javascript">
$(function(){
    editormd.markdownToHTML("editormd-view", {
        htmlDecode: "style, script, iframe",
        emoji: true,
        taskList:true,
        tex:true,
        flowChart:true,
        sequenceDiagram : true,
    });
});

function like_article(id, action){
    $.ajax({
        url: "{% url 'article:like_article' %}",
        type: "POST",
        data: {"id":id, "action":action},
        success: function(e){
            if(e=="1"){
                layer.msg("感谢点赞");
                window.location.reload();
            }else{
                layer.msg("我会继续努力");
                window.location.reload();
            }
        },
    });
}
</script>
{% endwith %}
{% endblock %}

打开文章详情,刷新页面,查看效果。


文章详情