• 评论功能和render渲染


    1.render渲染

    1.js代码放在HTML中
    render返回页面,并将返回的数据渲染到而面上。即页面上只要有{{}}就渲染,
    但是在js代码中,使用{{}},得不到渲染的值,原因是{{}}未定义,js时一种语言,所有的变量都需要定义才能使用。
    比如在python中输入a,运行报错,输入’a' 运行,就没问题。因此,在js中更需要为{{}}定义类型
    var article_id="{{ article.pk }}"; 加入引号,定义为str
    2.js变为静态文件(即放到单独的文件中)
    var article_id="{{ article.pk }}";失效,会渲染不了。将js代码放到这个文件中,在HTML中引入<script src="/static/myarticle.js"></script>
    由于render遇到{{}}才会渲染,而在当前HTML中<script src="/static/myarticle.js"></script>中并没有{{}}
    因此js代码中数据渲染不了
    解决方法:在HTML中新建标签,将js代码中需要的数据,添加到HTML中,这样js通过找到HTML中这个标签进行取值
    在HTNL中添加标签:属性设置为需要的属性
    <div class="info" article_id="{{ article.pk }}" username="{{ request.user.username }}"></div>
    js中取值:
    var article_id = $(".info").attr("article_id");

    2.评论功能

    1.在页面上显示出所有评论。即在处理article_detail函数时,从数据库中取得对应文章的评论表
    渲染到页面
    2.用户评论:
    1.在文章处理页面,制作评论区,在评论框中显示出用户的昵称
    2.判断用户是否登陆,如果未登陆,就去登陆,已登陆就做评论操作
    3.用户评论分为根评论(直接输入评论)和子评论(回复别人),在子评论点击回复时,光标移到评论框内。设置一个属性区分是子评论还是跟评论。设置pid=""
    4.如果是回复,就为其添加@用户名的功能
    5.提交评论,判断是根评论还是子评论,如果是子评论,就将@用户名给去掉,通过索引进行切片
    6.向后台发送数据,后台取到传递过来的文章id,pid和内容,并取到评论人的id,判断pid
    7.如果是根评论,就将评论信息写到评论表中,如果是子评论,需将额外的付评论用户ip写进去
    8.将评论内容,创建时间,用户名传给ajax
    9.ajax接收到数据后,在评论例表中加入新拼接的标签
    //拼接使用++
    var comment_li= '<li class="list-group-item"><div><span style="color: gray">' + create_time + '</span> &nbsp;&nbsp; <a href=""><span>' + username + '</span></a></div> <div class="con"> <p> ' + content + ' </p> </div> </li>';
    $(".comment_list").append(comment_li);
    10.清空文本框并将pid重新设置为空

    3.评论树

    '''
    def comment_tree(request,article_id):
    
        ret=list(models.Comment.objects.filter(article_id=article_id).values("pk","content","parent_comment_id"))
        print(ret)
        return JsonResponse(ret,safe=False)
     // 获取评论数据,展示评论树结构
            $.ajax({
                url: "/blog/comment_tree/" + '{{ article.pk }}/',
                success: function (data) {
                    console.log(data);
    
                    $.each(data, function (index, comment_dict) {
                        var s = '<div class="comment_item" comment_id=' + comment_dict.pk + '> <span class="content">' + comment_dict.content + '</span> </div>'
                        if (comment_dict.parent_comment_id) {
                            // 子评论
                            pid=comment_dict.parent_comment_id;
                            $("[comment_id="+pid+"]").append(s);
                        }
                        else {   //  根评论
                            $(".comment_tree").append(s);
                        }
                    })
    
    
                }
            });
    
    '''
    View Code

    4.评论功能代码

    '''
    {% block page-main %}
    
        <div class="article-detail">
            <h1>{{ article.title }}</h1>
    {#        <h3>{{ article.desc }}</h3>#}
            <p>{{ article.articledetail.content|safe }}</p>
        </div>
        <div class="poll clearfix">
            <div id="div_digg">
            <div class="diggit action">
                <span class="diggnum" id="digg_count">{{ article.up_count }}</span>
            </div>
            <div class="buryit action">
                <span class="burynum" id="bury_count">{{ article.down_count }}</span>
            </div>
            <div class="clear"></div>
            <div class="diggword" id="digg_tips" style="color: red;"></div>
        </div>
        </div>
        <p>评论列表</p>
        <ul class="comment_list">
            {% for comment in comment_list %}
                <li class="list-group-item">
                    <div>
                        <a href="">#{{ forloop.counter }}楼</a> &nbsp;&nbsp;
                        <span style="color: gray">{{ comment.create_time|date:"Y-m-d H:i" }}</span> &nbsp;&nbsp;
                        <a href=""><span>{{ comment.user.username }}</span></a>
                        <a class="pull-right reply_btn" username="{{ comment.user.username }}"
                           comment_pk="{{ comment.pk }}"><span>回复</span></a>
                    </div>
                    {#   父评论             #}
                    {% if comment.parent_comment_id %}
                        <div class="pid_info well">
                            <p> {{ comment.parent_comment.user.username }}:
                                &nbsp;&nbsp;&nbsp;{{ comment.parent_comment.content }} </p>
                        </div>
                    {% endif %}
                    <div class="con">
                        <p>
                            {{ comment.content }}
                        </p>
                    </div>
                </li>
            {% endfor %}
        </ul>
        //评论功能
        {% if request.user.username %}
            <div class="div_comment">
                <p>昵称:<input type="text" id="tbCommentAuthor" class="author" disabled="disabled" size="50"
                             value="{{ request.user.username }}"></p>
                <p>评论内容</p>
                <textarea name="" id="comment_content" cols="60" rows="10"></textarea>
                <p>
                    <button id="comment_btn" style="margin-top: 20px">提交评论</button>
                </p>
    
            </div>
        {% else %}
            <a href="/login/">登录</a>
        {% endif %}
        {#自定义一个属性标签,便用后续使用属性值,并且当js设置为静态文件时,时必须要用到的    #}
         <div class="info" article_id="{{ article.pk }}" username="{{ request.user.username }}"></div>
    
    {% endblock %}
    {%  block page_js %}
        {% csrf_token %}
        <script>
            $("#div_digg .action").on("click",function () {
                //判断是点赞还是踩灭,注意不能是diggnum
                if($(".info").attr("username")){
                   var is_up=$(this).hasClass("diggit");
                console.log(is_up);
                 //获取到文章id 在js中需要加引号
                var article_id="{{ article.pk }}";
                $.ajax({
                    url:"/blog/up_down/",
                    type:"post",
                    data:{
                        "is_up":is_up,
                        "article_id":article_id,
                        "csrfmiddlewaretoken":$("[name='csrfmiddlewaretoken']").val(),
                    },
                    success:function(data){
                        alert(data);
                        //如果为真,说明是第一次操作
                        //console.log(data.state); 都可以使用
                        console.log(data["state"]);
                        if(data.state){
                            if(is_up){
                                var val=$("#digg_count").text();  //点赞加1
                                val=parseInt(val)+1;
                                console.log(val);
                                $("#digg_count").text(val);
                            }else{
                                 var val=$("#bury_count").text();
                                val=parseInt(val)+1;
                                $("#bury_count").text(val); //踩加1
                            }
                        }else{
                            var val=66;
                            console.log(val);
                            if(data.first_action){
                                  $("#digg_tips").html("您已经推荐过");
                            }else {
                                 $("#digg_tips").html("您已经反对过");
    
                            }
                        }
    
    
    
                    }
    
                    }
    
                )
                }else{
                     location.href = "/login/"
                    }
    
    
            });
    
            //提交评论 pid为空就是根评论,不为空就是子评论
            var pid="";
            $("#comment_btn").on("click",function () {
                var article_id='{{ article.pk }}';
                var content=$("#comment_content").val();
                console.log(article_id,content);
                if(pid) {
                    //子评论时,要有@父评论用户,然后再填评论,在存评论时只存评论内容,因此用到切割
                    var index=content.indexOf("
    ");
                    content=content.slice(index+1)
                }
                $.ajax({
                    url:"/blog/comment/",
                    type:"post",
                    data:{
                        article_id:article_id,
                        content:content,
                        pid:pid,
                        csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val(),
                    },
                    success:function (data) {
                        alert(data)
                        var create_time=data.create_time;
                        var content=data.content;
                        var username=data.username;
                        //拼接使用++
                        var comment_li= '<li class="list-group-item"><div><span style="color: gray">' + create_time + '</span> &nbsp;&nbsp; <a href=""><span>' + username + '</span></a></div> <div class="con"> <p> ' + content + ' </p> </div> </li>';
                         $(".comment_list").append(comment_li);
                         // 清空文本框
                        $("#comment_content").val('');
                        // 清空pid
                        pid = ""
                    }
                })
            });
            //回复功能
            $(".list-group-item .reply_btn").on("click",function () {
                //点击回复的时候,光标移到评论框
                $("#comment_content").focus();
                //得到属性为username的值
                var v="@"+$(this).attr("username")+"
    ";
                $("#comment_content").val(v)
                  //pid赋值
                pid = $(this).attr("comment_pk")
            })
        </script>
    {% endblock %}
    
    
    '''
    HTML
    '''
    def article_detail(request, username, pk):
        """
        :param username: 被访问的blog的用户名
        :param pk: 访问的文章的主键id值
        :return:
        """
        user = models.UserInfo.objects.filter(username=username).first()
        if not user:
            return HttpResponse("404")
        blog = user.blog
        # 找到当前的文章
        article_obj = models.Article.objects.filter(pk=pk).first()
        # 所有评论列表
        comment_list = models.Comment.objects.filter(article_id=pk)
    
        return render(
            request,
            "article_detail.html",
            {
                "username": username,
                "article": article_obj,
                "blog": blog,
                "comment_list": comment_list
             }
        )
    
    def comment(request):
        if request.method=='POST':
            article_id=request.POST.get("article_id")
            pid=request.POST.get("pid")
            content=request.POST.get("content")
            user_pk=request.user.pk
            response = {}
            if not pid:  #此时是根评论
                comment_obj=models.Comment.objects.create(article_id=article_id,user_id=user_pk,content=content)
            else:  #此时是子评论,要添加父评论的id
                comment_obj=models.Comment.objects.create(article_id=article_id, user_id=user_pk, content=content,parent_comment_id=pid)
            response["create_time"]=comment_obj.create_time.strftime("%Y-%m-%d") #comment_obj.create_time是个日期对象,需要转换
            response["content"]= content
            response["username"] = comment_obj.user.username
            return JsonResponse(response)
    '''
    View
     
     
  • 相关阅读:
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
  • 原文地址:https://www.cnblogs.com/zgf-666/p/9129581.html
Copyright © 2020-2023  润新知