美文网首页工具
十九、Django2.1 搭建多用户的博客网站——使用自定义模板

十九、Django2.1 搭建多用户的博客网站——使用自定义模板

作者: 27efec53a72d | 来源:发表于2019-02-27 22:49 被阅读664次

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

    服务器环境搭建(选学)

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

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

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

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

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

    正文:

    {% if %} 和 {% for %}这些是Django模板中的默认标签,为了应对更多复杂的操作,Django还允许开发者自定义模板标签,共有三种自定义模板标签,分别是simple_tag、inclusion_tag、assignment_tag。

    下面我们将通过实例分别使用以上三种自定义模板标签。

    在 ./articles 中创建一个目录 templatetags,这个目录名称是Django默认的,必须使用这个名称,不能更改。然后在里面创建两个文件 __ init __.py(init两边分别是两个下划线) 和 article_tags.py

    1、使用自定义模板标签显示文章总数

    编辑 ./article/templatetags/article_tags.py

    from django import template
    
    register = template.Library()
    from article.models import ArticlePost
    
    
    @register.simple_tag
    def total_articles():
        return ArticlePost.objects.count()
    

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

    {% extends "base.html" %} 
    

    下面增加

     {% load article_tags %}
    

    然后在这行代码

    <h1>阅读,丰富头脑,善化行为</h1>
    

    下面增加

     <p>这里已经有{% total_articles %}篇文章供你阅读</p>
    

    完整的./templates/article/list/article_titles.html代码如下:

    {% extends "base.html" %}
    {% load article_tags %}
    {% block title %} articles {% endblock %}
    {% block content %}
    <div class="row text-center vertical-middle-sm">
        <h1>阅读,丰富头脑,善化行为</h1>
        <p>这里已经有{% total_articles %}篇文章供你阅读</p>
    </div>
    <div class="container">
        {% for article in articles %}
        <div class="list-group">
            <a href="{{article.get_url_path}}" class="list-group-item active">
                <h4 class="list-group-item-heading">{{article.title}}</h4>
            </a>
            <p class="list-group-item-text">作者:<a href="{% url 'article:author_articles' article.author.username %}">{{article.author.username}}</a></p>
            <p class="list-group-item-text">概要:{{article.body|slice:'70'| linebreaks}}</p>
        </div>
        {% endfor %}
        {% include "paginator.html" %}
    </div>
    {% endblock %}
    

    运行Django,打开文章详情,查看效果


    显示文章总数

    2、使用自定义模板标签显示某一个作者的文章总数

    编辑 ./article/templatetags/article_tags.py 新增以下代码

    @register.simple_tag
    def author_total_articles(user):
        return user.article.count()
    

    修改 ./templates/article/list/author_articles.html
    同样的,增加

     {% load article_tags %}
    

    然后在这行代码

    <p>{{ user.username }}</p>
    

    下面增加

     <p>共发表{% author_total_articles user %}篇文章</p>
    

    完整的./templates/article/list/author_articles.html代码如下

    {% extends "base.html" %}
    {% load article_tags %}
    {% load staticfiles %}
    {% block title %}articles{% endblock %}
    {% block content %}
    <div class="row text-center vertical-middle-sm">
        <h1>阅读,丰富头脑,善化行为</h1>
    </div>
    <div class="container">
        <div class="col-md-8">
            {% for article in articles %}
            <div class="list-group">
                <a href="{{article.get_url_path}}" class="list-group-item active">
                    <h4 class="list-group-item-heading">{{article.title}}</h4>
                </a>
                <p class="list-group-item-text">作者:
                    <a href="{% url 'article:author_articles' article.author.username %}">{{article.author.username}}</a>
                </p>
                <p class="list-group-item-text">概要:{{article.body|slice:'70'|linebreaks}} </p>
            </div>
            {% endfor %}
            {% include "paginator.html" %}
        </div>
        <div class="col-md-4">
            <div>
                {% if userinfo.photo %}
                <img src="{{ userinfo.photo | striptags }}" class="img-circle" id="my_photo" name="user_face" style="width: 300px">
                {% else %}
                <img name="user_face" src="{% static 'images/newton.jpg' %}" class="img-circle" id="my_photo" style="width: 300px">
                {% endif %}
            </div>
            <div>
                <p>{{ user.username }}</p>
                <p>共发表{% author_total_articles user %}篇文章</p>
                {% if userinfo %}
                <p>{{ userinfo.company }}</p>
                <p>{{ userinfo.aboutme }}</p>
                {% else %}
                <p>这个作者太懒了,什么也没有留下。</p>
                {% endif %}
            </div>
        </div>
    </div>
    {% endblock %}
    

    点击文章列表中的作者,效果如图


    某一作者的文章列表

    3、使用自定义模板标签显示最新发布的文章

    编辑 ./article/templatetags/article_tags.py 新增latest_articles

    @register.inclusion_tag('article/list/latest_articles.html')
    def latest_articles(n=5):
        latest_articles = ArticlePost.objects.order_by("-created")[:n]
        return {"latest_articles": latest_articles}
    

    创建 ./templates/article/list/latest_articles.html

    <ul>
        {% for article in latest_articles %}
        <li>
            <a href="{{ article.get_url_path }}">{{ article.title }}</a>
        </li>
        {% endfor %}
    </ul>
    

    修改 ./templates/article/list/article_content.html
    增加

     {% load article_tags %}
    

    然后在"最受欢迎文章"之后增加以下代码

    <hr>
            <p class="text-center">
            <h3>最新文章</h3></p>
            {% latest_articles 4 %}
    

    点击某篇文章,效果如图


    显示最新文章

    4、使用自定义模板标签显示评论最多的文章

    编辑 ./article/templatetags/article_tags.py 新增most_commented_articles

    from django.db.models import Count
    
    @register.simple_tag
    def most_commented_articles(n=3):
        return ArticlePost.objects.annotate(total_comments=Count('comments')).order_by("-total_comments")[:n]
    

    修改 ./templates/article/list/article_content.html 在"最新文章"之后增加以下代码

    <hr>
            <p class="text-center">
            <h3>最多评论文章</h3></p>
            {% most_commented_articles as most_comments %}
            <ul>
                {% for comment_article in most_comments %}
                <li>
                    <a href="{{comment_article.get_url_path}}">{{ comment_article.title }}</a>
                </li>
                {% endfor %}
            </ul>
    

    完整的./templates/article/list/article_content.html代码如下

    {% extends "base.html" %}
    {% load article_tags %}
    {% 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>
                <h3><span class="glyphicon glyphicon-bullhorn"></span>本文有{{ comments.count }}评论</h3>
                {% for comment in article.comments.all %}
                <div>
                    <p><strong>{{ comment.commentator }}</strong>说:</p>
                    <p style="margin-left:40px;">{{ comment.body }}</p>
                </div>
                {% empty %}
                <p>没有评论</p>
                {% endfor %}
    
                <h3><span class="glyphicon glyphicon-send"></span>看文章,发评论,不要沉默</h3>
                <form action="." method="post" class="form-horizontal" role="form">{% csrf_token %}
                    <div class="form-group">
                        <label for="inputEmail3" class="col-sm-2 control-label">评论员</label>
                        <div class="col-sm-10">
                            {{ comment_form.commentator}}
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="inputEmail3" class="col-sm-2 control-label">评论</label>
                        <div class="col-sm-10">
                            {{ comment_form.body }}
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <p><input type="submit" name="" value=" 发 评 论 " class="btn btn-primary"></p>
                        </div>
                    </div>
                </form>
            </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>
    
            <hr>
            <p class="text-center">
            <h3>最新文章</h3></p>
            {% latest_articles 4 %}
    
            <hr>
            <p class="text-center">
            <h3>最多评论文章</h3></p>
            {% most_commented_articles as most_comments %}
            <ul>
                {% for comment_article in most_comments %}
                <li>
                    <a href="{{comment_article.get_url_path}}">{{ comment_article.title }}</a>
                </li>
                {% endfor %}
            </ul>
        </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 %}
    

    点击某篇文章,效果如图


    显示最多评论文章

    相关文章

      网友评论

        本文标题:十九、Django2.1 搭建多用户的博客网站——使用自定义模板

        本文链接:https://www.haomeiwen.com/subject/ksaneqtx.html