BBS项目分布搭建五(评论相关功能实现)
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项目分布搭建五(评论相关功能实现)的更多相关文章
- BBS项目分布搭建四(点赞点踩及评论功能准备)
BBS项目分布搭建四(点赞点踩及评论功能) 1. 点赞点踩样式准备 # 在base.html文件中 head标签内 添加css模块: {% block css %} {% endblock %} # ...
- BBS项目分布搭建二(个人站点相关)
BBS项目分布搭建二 1. 首页详情补充 # 在home.html文件中 body标签内补充: <div class="container-fluid"> <di ...
- BBS项目分布搭建三(个人站点时间归档补充,实现侧边栏跳转、无线级分类、实现文章详情页展示功能)
BBS项目分布搭建三(个人站点时间归档补充,) 1. 个人站点时间归档 """ settings.py设置最好更改以下: LANGUAGE_CODE = 'zh-hans ...
- bbs项目实现点赞和评论的功能
一.点赞功能 思路是这样的: 1.对点赞和踩都设置一个相同的class,然后对这个class绑定点击事件 2.点击触发ajax请求,我们对赞的标签设置了一个class属性,对踩的标签没有设置这个cla ...
- BBS项目补充知识(后台文章展示功能)
BBS项目补充知识 1. 开放 media 文件路径 # 以用户注册页面为例 用户头像文件我们默认时保存在 根路径下的static下的img文件夹 但也可以单独放置在指定路径下 # 根路径下创建 me ...
- .Net Core3.0 WebApi 项目框架搭建 五: 轻量型ORM+异步泛型仓储
.Net Core3.0 WebApi 项目框架搭建:目录 SqlSugar介绍 SqlSugar是国人开发者开发的一款基于.NET的ORM框架,是可以运行在.NET 4.+ & .NET C ...
- .Net Core3.0 WebApi 项目框架搭建 五:仓储模式
.Net Core3.0 WebApi 项目框架搭建:目录 理论介绍 仓储(Respository)是存在于工作单元和数据库之间单独分离出来的一层,是对数据访问的封装.其优点: 1)业务层不需要知道它 ...
- 如何在项目中使用composer的相关功能
最近要在公司的magento项目中引用第三方库,用了composer来进行管理,composer还是非常方便的: 1.在应用的根目录下添加文件:composer.json { "nam ...
- 潭州课堂25班:Ph201805201 django 项目 第十五课 用户注册功能后台实现 (课堂笔记)
前台:判断用户输入 ,确认密码,手机号, 一切通过后向后台发送请求, 请求方式:post 在 suers 应用下的视图中: 1,创建个类, 2,创建 GET 方法,宣言页面 3,创建 POST 方法 ...
随机推荐
- 学习JDBC遇到的一些问题
1. 数据库版本与驱动对应问题 参考官方文档:https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-versions.html 具体详情还需 ...
- 利用纯代码写出一个秒表表盘的方法 —— #DF
@interface ViewController () @property (nonatomic, strong) CALayer *secLayer; // 秒针layer @property ( ...
- 【NetCore】依赖注入的一些理解与分享
依赖注入 DI 前言 声明:我是一个菜鸟,此文是自己的理解,可能正确,可能有误.仅供学习参考帮助理解,如果直接拷贝代码使用造成损失概不负责. 相关的文章很多,我就仅在代码层面描述我所理解的依赖注入是个 ...
- 详解Java12新增语法switch表达式
引言 在学习分支语句的时候,我们都学过 switch 语句,相比于 if-else 语句,他看起来更加整洁,逻辑更加清晰,Java中当然也给我们提了相关的 switch 方法.但是Java的强大之处在 ...
- CentOS虚拟机关闭防火墙
关闭防火墙 systemctl stop firewalld 关闭防火墙开机自启动 systemctl disable firewalld 关闭安全机制,将selinux设置为disabled vi ...
- Linux基础:操作系统的启动
Centos6: # 1.加电自检(BIOS)# 2.MBR引导(512k)dd </dev/zero >/dev/sda bs=1k count=400 # 3.GRUB菜单(选择系统) ...
- Solution -「ARC 126F」Affine Sort
\(\mathcal{Description}\) Link. 给定 \(\{x_n\}\),令 \[f(k)=\left|\{(a,b,c)\mid a,b\in[0,c),c\in[1,k ...
- Session是什么?它与Cookie有什么区别?
你好,是我琉忆. 今天我们讲一讲Session与Cookie的区别 1.Session对象 上一节简单介绍了Cookie,接下来简单介绍Session.Session和Cookie都是会话管理技术的一 ...
- linux可以这样玩 之 杂乱无章的随笔(不定期更新)
文章目录 快速重命名 vim的进化 vim高亮当前行 vim列编辑 vim块编辑 vim行编辑 vim 中替换内容 vim保留当前已经编辑的内容,切换到其他用户继续编辑 修改服务的进程限制 CentO ...
- Python中random模块的用法案例
1 import random # 调用random模块 2 3 a = random.random() # 随机从0-1之间抽取一个小数 4 print(a) 5 6 a = random.rand ...