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>



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;
}

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>

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 %}

BBS项目分布搭建五(评论相关功能实现)的更多相关文章

  1. BBS项目分布搭建四(点赞点踩及评论功能准备)

    BBS项目分布搭建四(点赞点踩及评论功能) 1. 点赞点踩样式准备 # 在base.html文件中 head标签内 添加css模块: {% block css %} {% endblock %} # ...

  2. BBS项目分布搭建二(个人站点相关)

    BBS项目分布搭建二 1. 首页详情补充 # 在home.html文件中 body标签内补充: <div class="container-fluid"> <di ...

  3. BBS项目分布搭建三(个人站点时间归档补充,实现侧边栏跳转、无线级分类、实现文章详情页展示功能)

    BBS项目分布搭建三(个人站点时间归档补充,) 1. 个人站点时间归档 """ settings.py设置最好更改以下: LANGUAGE_CODE = 'zh-hans ...

  4. bbs项目实现点赞和评论的功能

    一.点赞功能 思路是这样的: 1.对点赞和踩都设置一个相同的class,然后对这个class绑定点击事件 2.点击触发ajax请求,我们对赞的标签设置了一个class属性,对踩的标签没有设置这个cla ...

  5. BBS项目补充知识(后台文章展示功能)

    BBS项目补充知识 1. 开放 media 文件路径 # 以用户注册页面为例 用户头像文件我们默认时保存在 根路径下的static下的img文件夹 但也可以单独放置在指定路径下 # 根路径下创建 me ...

  6. .Net Core3.0 WebApi 项目框架搭建 五: 轻量型ORM+异步泛型仓储

    .Net Core3.0 WebApi 项目框架搭建:目录 SqlSugar介绍 SqlSugar是国人开发者开发的一款基于.NET的ORM框架,是可以运行在.NET 4.+ & .NET C ...

  7. .Net Core3.0 WebApi 项目框架搭建 五:仓储模式

    .Net Core3.0 WebApi 项目框架搭建:目录 理论介绍 仓储(Respository)是存在于工作单元和数据库之间单独分离出来的一层,是对数据访问的封装.其优点: 1)业务层不需要知道它 ...

  8. 如何在项目中使用composer的相关功能

    最近要在公司的magento项目中引用第三方库,用了composer来进行管理,composer还是非常方便的: 1.在应用的根目录下添加文件:composer.json {    "nam ...

  9. 潭州课堂25班:Ph201805201 django 项目 第十五课 用户注册功能后台实现 (课堂笔记)

    前台:判断用户输入 ,确认密码,手机号, 一切通过后向后台发送请求, 请求方式:post 在 suers 应用下的视图中: 1,创建个类, 2,创建 GET 方法,宣言页面 3,创建  POST 方法 ...

随机推荐

  1. C++网络编程卷1、卷2概述

    转载请注明来源:https://www.cnblogs.com/hookjc/ 一:  C++NPv1主要涉及到的类: 1.1.  Logging_Server 是个抽象类,用来定义接口类型,此类不能 ...

  2. MSTP多生成树协议

    MSTP多生成树协议 目录 MSTP多生成树协议 1.MSTP(Multiple Spanning Tree Protocol)概述 2.STP.RSTP.PVST的应用缺陷 3.MSTP的主要特点 ...

  3. JAVA String介绍、常量池及String、StringBuilder和StringBuffer得区别. 以及8种基本类型的包装类和常量池得简单介绍

    一.概述 String是代表字符串的类,本身是一个最终类,使用final修饰,不能被继承. 二.定义方式   方式一:直接赋值法 String str1 = "hello"; 方式 ...

  4. 关于单调性优化DP算法的理解

    Part1-二分栈优化DP 引入 二分栈主要用来优化满足决策单调性的DP转移式. 即我们设\(P[i]\)为\(i\)的决策点位置,那么\(P[i]\)满足单调递增的性质的DP. 由于在这种DP中,满 ...

  5. Fiddler监听Https请求响应

    Fiddler问题 - creation of the root certificate was not successful 解决办法: http://localhost:8888/    安装证书 ...

  6. 06.python语法入门--与用户交互、运算符

    与用户交互 输入 input    # python2与python3的区别        '''python3'''    # 将获取到的用户输入赋值给变量名res    res = input(' ...

  7. Solution -「CF 923E」Perpetual Subtraction

    \(\mathcal{Description}\)   Link.   有一个整数 \(x\in[0,n]\),初始时以 \(p_i\) 的概率取值 \(i\).进行 \(m\) 轮变换,每次均匀随机 ...

  8. Python小游戏之 - 飞机大战 !

    用Python写的"飞机大战"小游戏 源代码如下: # coding=utf-8 import random import os import pygame # 用一个常量来存储屏 ...

  9. shell切割nginx日志

    用linux自带的计划任务切割nginx日志,每天0点执行 #!/bin/bash #GuoYabin nginxpid=`/bin/ps aux|grep nginx |awk /master/'{ ...

  10. 【测试必备】k8s基本使用(更新中。。。)

    测试为什么要学习容器技术及k8s k8s不是运维的专属技术 随着互联网技术的发展,架构也已经从单体架构发展到容器云( "微服务 + k8s" 完美结合) 很多人认为,k8s只是运维 ...