1、视图函数
# 不需要登录装饰器,匿名用户也可访问def article_detail(request, id, slug): # print(slug,id) article = get_object_or_404(ArticlePost, id=id, slug=slug) # 连接redis r = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB) # 总的访问次数,访问一次就+1,一般命名规则为"对象类型:对象ID:对象属性" total_views = r.incr(‘article:{}:views‘.format(article.id)) # zincrby(name, amount, value)方法:根据amount设定的步长增加有序集合name中的value的分值(类似于权重) # 实现了每访问一次文章就会将article_ranking中的article.id分值增加1 # article_ranking中存放的是文章的id用来代表文章,每访问一次该文章就会增加文章的分值 r.zincrby(‘article_ranking‘, 1, article.id) # 获取分值排名前十的对象 article_ranking = r.zrange(‘article_ranking‘, 0, -1, desc=True)[:10] # 获取排名前十文章的id列表,使用的是列表推导式,先进行for循环,再将每次的的值带入int()方法运算,将结果放在新的列表中 article_ranking_ids = [int(id) for id in article_ranking] print(‘文章浏览量对应的id:%s‘ % article_ranking_ids) # 查询出排名在前十的文章对象,并放在list中。注意id__in用法:id在article_ranking_ids列表中 most_viewed = list(ArticlePost.objects.filter(id__in=article_ranking_ids)) print(‘文章未排序:%s‘ % most_viewed) # 将获得的列表按照下表索引进行排序,lamda为匿名函数,先运算后面表达式,冒号前的x相当于参数,代表most_viewed列表中文章对象 # 按照文章的id得到对应的下标,再按照下标进行排序 most_viewed.sort(key=lambda x: article_ranking_ids.index(x.id)) print(‘文章已经排序:%s‘ % most_viewed) return render(request, ‘article/column/article_detail.html‘, {‘article‘: article, ‘total_views‘: total_views, ‘most_viewed‘: most_viewed})
2、前端页面
{% extends ‘article/base.html‘ %}{% load staticfiles %}{% block title %}article detail{% endblock %} {% block content %}<div class="container"> <div class="col-md-9"> <header> <h1>{{ article.title }}</h1> <p>{{ user.username }} {{ total_views }}次阅读</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> <div class="col-md-3"> <p class="text-center">最受欢迎文章</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"> $(function () { editormd.markdownToHTML("editormd-view",{ htmlDecode:"style,script,iframe", emoji:true, tasklist:true, flowChart:true, tex:true, sequenceDiagram:true, }); }); </script>{% endblock %}
原文地址:https://www.cnblogs.com/gcgc/p/10670528.html
时间: 2024-11-06 14:44:14