jgx0

BBS项目分布搭建五(评论相关)

1. 根评论逻辑实现

# 在models.py文件中 修改:
# 7. 评论表
    parent = models.ForeignKey(to='self', null=True)
    
    
# 添加路由(最好放在文章详情之上):
    # 评论功能
    url(r'^comment/', views.comment),
    
    
# 在views.py中 添加功能:
# 10. 评论功能
def comment(request):
    if request.is_ajax() and request.method == 'POST':
        back_dic = {'status': 200, 'msg': '评论成功'}


        # 1. 接收参数
        content = request.POST.get('content')
        article_id = request.POST.get('article_id')


        # 2. 验证参数
        if not content:
            back_dic['status'] = 1013
            back_dic['msg'] = '评论内容不能为空哦~'
            return JsonResponse(back_dic)

        if not article_id:
            back_dic['status'] = 1014
            back_dic['msg'] = '评论的文章不存在'
            return JsonResponse(back_dic)


        # 3. 验证是否登录,验证尽量的完善
        if not request.session.get('username'):
            back_dic['status'] = 1015
            back_dic['msg'] = '请先登录在评论'
            return JsonResponse(back_dic)


        # 4. 处理评论逻辑
        # 4.1 操作评论表,文章表(评论数)
        # 3.2 事务:保证数据安全,ACID四大特性,原子性,保证的是同一个事务中的SQL必须同时成功,同时失败
        # 3.3 在企业中,遇到跟财务相关的需求,尽量都要使用事务
        from django.db import transaction

        with transaction.atomic():
            models.Article.objects.filter(pk=article_id).update(comment_num=F('comment_num') + 1)
            models.Comment.objects.create(
                content=content,
                article_id=article_id,
                user_id=request.session.get('id'),
            )
        return JsonResponse(back_dic)

    return HttpResponse('ok')



# 修改article_detail.html文件
# 在 {% block content %} 标签中添加以下内容:
    {#    评论样式开始#}
    {% if request.session.username %}
    <div >
        <p>
            <span class="glyphicon glyphicon-comment"></span>发表评论
        </p>
        <p>
            <textarea name="" id="content" cols="30" rows="10"></textarea>
        </p>
        <p>
            <input type="button" class="btn btn-success commit" value="提交">
        </p>
    </div>
    {% endif %}
    {#    评论样式结束#}
        

# 在 {% block js %} </script> 标签中添加以下内容:
        // 提交评论
        $(".commit").click(function () {
            // 先获取评论内容
            var content = $('#content').val();
            var article_id = '{{ article_id }}';  // 拿到文章id比对

            // 提交ajax
            $.ajax({
                url: '/comment/',
                type: 'post',
                data: {'content': content, article_id: article_id, },
                success: function (res) {
                    console.log(res);
                }
             })
        })
    </script>

image
image

2. 评论内容前端列表样式准备

# 修改article_detail.html文件
# 在 {% block content %}标签中添加:
    
    {#    评论列表开始#}
    <div class="comment">
        <h1>评论列表</h1>
        <ul class="list-group">
                <li class="list-group-item">
                    <span style="margin-right: 10px;color: #399ab2"># 1楼</span> <span style="margin-right: 10px">2022-03-08</span> <span style="color: #399ab2">吾 荒天帝</span>
                    <span style="margin-right: 10px">{{ comment.create_time|date:'Y-m-d H:i' }}</span>
                    <span style="color: #399ab2">{{ comment.user.username }}</span>
                    <span><a href="" class="pull-right reply" style="text-decoration: none;">回复</a></span>
                    <p style="margin-top: 10px;margin-left: 15px;">
                        一剑断万古! 他化自在,他化万古!
                    </p>
                </li>
        
                <li class="list-group-item">
                    <span style="margin-right: 10px;color: #399ab2"># 1楼</span> <span style="margin-right: 10px">2022-03-08</span> <span style="color: #399ab2">吾 荒天帝</span>
                    <span style="margin-right: 10px">{{ comment.create_time|date:'Y-m-d H:i' }}</span>
                    <span style="color: #399ab2">{{ comment.user.username }}</span>
                    <span><a href="" class="pull-right reply" style="text-decoration: none;">回复</a></span>
                    <p style="margin-top: 10px;margin-left: 15px;">
                        一剑断万古! 他化自在,他化万古!
                    </p>
                </li>    
        
                <li class="list-group-item">
                    <span style="margin-right: 10px;color: #399ab2"># 1楼</span> <span style="margin-right: 10px">2022-03-08</span> <span style="color: #399ab2">吾 荒天帝</span>
                    <span style="margin-right: 10px">{{ comment.create_time|date:'Y-m-d H:i' }}</span>
                    <span style="color: #399ab2">{{ comment.user.username }}</span>
                    <span><a href="" class="pull-right reply" style="text-decoration: none;">回复</a></span>
                    <p style="margin-top: 10px;margin-left: 15px;">
                        一剑断万古! 他化自在,他化万古!
                    </p>
                </li>
        
                <li class="list-group-item">
                    <span style="margin-right: 10px;color: #399ab2"># 1楼</span> <span style="margin-right: 10px">2022-03-08</span> <span style="color: #399ab2">吾 荒天帝</span>
                    <span style="margin-right: 10px">{{ comment.create_time|date:'Y-m-d H:i' }}</span>
                    <span style="color: #399ab2">{{ comment.user.username }}</span>
                    <span><a href="" class="pull-right reply" style="text-decoration: none;">回复</a></span>
                    <p style="margin-top: 10px;margin-left: 15px;">
                        一剑断万古! 他化自在,他化万古!
                    </p>
                </li>
        
                <li class="list-group-item">
                    <span style="margin-right: 10px;color: #399ab2"># 1楼</span> <span style="margin-right: 10px">2022-03-08</span> <span style="color: #399ab2">吾 荒天帝</span>
                    <span style="margin-right: 10px">{{ comment.create_time|date:'Y-m-d H:i' }}</span>
                    <span style="color: #399ab2">{{ comment.user.username }}</span>
                    <span><a href="" class="pull-right reply" style="text-decoration: none;">回复</a></span>
                    <p style="margin-top: 10px;margin-left: 15px;">
                        一剑断万古! 他化自在,他化万古!
                    </p>
                </li>
        </ul>
    </div>
    {#    评论列表结束#}
        
        

# 在 {% block css %} <style> 标签中添加:
        .reply:hover {
            color: #9cba39;
        }
    

image

image

3. 评论后端逻辑实现

# 在views.py中 文章详情页功能中添加查询评论内容:
# 8. 文章详情页
    # 查询当前文章的所有评论
    comment_list = models.Comment.objects.filter(article_id=article_id).all()

    return render(request, 'article_detail.html', locals())



# 修改article_detail.html文件
# 修改 {% block js %} </script> 标签内的 // 提交ajax:
            // 提交ajax
            $.ajax({
                url: '/comment/',
                type: 'post',
                data: {'content': content, article_id: article_id, },
                success: function (res) {
                    console.log(res);
                    var userName = '{{ request.session.username }}'

                    if (res.status == 200) {
                        // 1. 清空评论框
                        $("#content").val('');

                        // 2. 把评论成功的信息放到页面上
                        $("#error_msg").text(res.msg);

                        // 3. 评论之后,渲染临时评论  // ``反引号 引用模板语法
                        var html = `
                            <li class="list-group-item">
                                <span class="glyphicon glyphicon-comment"></span>
                                <span style="color: #399ab2">${userName}</span>
                                <p style="    margin-top: 10px;margin-left: 15px;">
                                    ${content}
                                </p>
                            </li>
                        `;

                        {#// 使用字符串引号也可以达到同样效果#}
                        {#var html = ""#}
                        {#html += '<li class="list-group-item">' +#}
                        {#    '<span class="glyphicon glyphicon-comment"></span>'#}
                        {#    + '<span style="color: #399ab2">' + userName + '</span>' +#}
                        {#    '<p style="    margin-top: 10px;margin-left: 15px;">' + content + '</p>' +#}
                        {#    '</li>';#}

                        $('.list-group').append(html);
                    }
                }
             })
        })
    </script>

image

4. 子评论功能实现

# 在views.py中修改 评论功能 两处:
# 10. 评论功能
        # 1. 接收参数
        content = request.POST.get('content')
        article_id = request.POST.get('article_id')
        parent_id = request.POST.get('parent_id')  # 一处
        
        
        with transaction.atomic():
            models.Article.objects.filter(pk=article_id).update(comment_num=F('comment_num') + 1)
            models.Comment.objects.create(
                content=content,
                article_id=article_id,
                user_id=request.session.get('id'),
                parent_id=parent_id  # 二处
            )
        return JsonResponse(back_dic)

    

# 将 {#    评论列表开始#} 下面的 <span><a标签的 href="" 删除 达到阻止a标签默认提交问题
	此外 也可以在 // 子评论 下数据提交中进行阻止
    
# 修改 article_detail.html文件:
# 修改 评论列表 内容:
    {#    评论列表开始#}
    <div class="comment">
        <h1>评论列表</h1>
        <ul class="list-group">
            {% for comment in comment_list %}
                <li class="list-group-item">
                    <span style="margin-right: 10px;color: #399ab2"># {{ forloop.counter }}楼</span>
                    <span style="margin-right: 10px">{{ comment.create_time|date:'Y-m-d H:i' }}</span>
                    <span style="color: #399ab2">{{ comment.user.username }}</span>
                    <span><a class="pull-right reply" style="text-decoration: none;" username="{{ comment.user.username }}" comment_id="{{ comment.pk }}">回复</a></span>

                    <p style="margin-top: 10px;margin-left: 15px;">
                        {% if comment.parent_id %}
                            <span>@ {{ comment.parent.user.username }}</span>
                            <p>
                                {{ comment.content }}
                            </p>
                        {% else %}
                            {{ comment.content }}
                        {% endif %}
                    </p>
                </li>

            {% endfor %}
        </ul>
    </div>
    {#    评论列表结束#}
    
        
        
# 修改 {% block js %} </script> 标签内容:
{% block js %}
    <script>
        var parent_id = null;  // 定义全局变量,目的是,在提交评论的事件里使用子评论事件里的根评论id
        $('.active').click(function () {
            var is_up = $(this).hasClass('diggit');  // true false
            var article_id = '{{ article_id }}';
            var _this = $(this)

            // 发送ajax请求
             $.ajax({
                url: '/up_or_down/',
                type: 'post',
                data: {'is_up': is_up, article_id: article_id},
                success: function (res) {
                    console.log(res);

                    if (res.status == 200) {
                        $('.error_msg').text(res.msg);
                        var old_num = Number(_this.children().text());
                        _this.children().text(old_num + 1)
                    } else if (res.status == 1010) {
                        $('.error_msg').append(res.msg)
                    } else {
                        layer.msg(res.msg)
                    }
                }
            })
        })

        // 提交评论
        $(".commit").click(function () {
            // 先获取评论内容
            var content = $('#content').val();
            var article_id = '{{ article_id }}';  // 拿到文章id比对

            // 重点:如何区分是根评论还是子评论
            if (parent_id) {
                // 子评论
                var num = content.indexOf('\n') + 1;
                content = content.slice(num)  // 把换行符之前的内容全部切掉
            }

            // 提交ajax
            $.ajax({
                url: '/comment/',
                type: 'post',
                data: {'content': content, article_id: article_id, parent_id: parent_id},
                success: function (res) {
                    console.log(res);
                    var userName = '{{ request.session.username }}'

                    if (res.status == 200) {
                        // 1. 清空评论框
                        $("#content").val('');

                        // 2. 把评论成功的信息放到页面上
                        $("#error_msg").text(res.msg);

                        // 3. 评论之后,渲染临时评论  // ``反引号 引用模板语法
                        var html = `
                            <li class="list-group-item">
                                <span class="glyphicon glyphicon-comment"></span>
                                <span style="color: #399ab2">${userName}</span>
                                <p style="    margin-top: 10px;margin-left: 15px;">
                                    ${content}
                                </p>
                            </li>
                        `;

                        {#// 使用字符串引号也可以达到同样效果#}
                        {#var html = ""#}
                        {#html += '<li class="list-group-item">' +#}
                        {#    '<span class="glyphicon glyphicon-comment"></span>'#}
                        {#    + '<span style="color: #399ab2">' + userName + '</span>' +#}
                        {#    '<p style="    margin-top: 10px;margin-left: 15px;">' + content + '</p>' +#}
                        {#    '</li>';#}

                        $('.list-group').append(html);

                        // 根评论的id要清空
                        parent_id = null;
                    }
                }
             })
        })

        // 子评论
        $('.reply').click(function (event) {
            {#alert(123)#}

            {#阻止a标签默认提交问题其他方法#}
            {#return false;  // 阻止默认提交, 不仅适用于a标签,还适用于form表单#}
            {#event.preventDefault() // 阻止默认提交#}

            // 子评论逻辑
            var userName = $(this).attr('username');

            // 获取根评论的id
            parent_id = $(this).attr('comment_id');
            var s = '@' + userName + '\n'
            $('#content').val(s).focus();
        })
    </script>
{% endblock %}

image

image

分类:

技术点:

相关文章: