python 评论楼
评论楼
从数据库中取出本篇博客的所有评论
使用python语句将评论整理成具有层级关系的列表
typename=request.POST.get('typename')
comment_list = models.comment.objects.filter(article_id=int(typename)).values("id", "content",
"user__nickname", "parent_id_id")
comment_dict = {}
for item in comment_list:
item["child"] = []
comment_dict[item['id']] = item
comment = []
for item in comment_list:
pid = item["parent_id_id"]
if pid:
comment_dict[pid]["child"].append(item)
else:
comment.append(item)
方式一:
后台生成html字符串(递归函数)
def comment_tree(comment_list):
# [{'child': [{'child': [{'child': [], 'user__nickname': 'egon', 'content': '哪里不好啊', 'create_time': None, 'id': 3, 'parent_id': 2}],
# 'user__nickname': 'sever', 'content': '扯淡', 'create_time': None, 'id': 2, 'parent_id': 1}],
# 'user__nickname': 'egon', 'content': '写的太好了', 'create_time': None, 'id': 1, 'parent_id': None},
# {'child': [], 'user__nickname': 'root', 'content': '写的不错', 'create_time': None, 'id': 4, 'parent_id': None},
# {'child': [], 'user__nickname': 'alex', 'content': '我写的真好', 'create_time': None, 'id': 5, 'parent_id': None}]
comment_str="<div class='comment'>"
for row in comment_list:
tpl="<div class='content'>%s:%s --- %s</div>"%(row['user__nickname'],row['content'],row['create_time'])
comment_str += tpl
if row['child']:
child_str=comment_tree(row['child'])
comment_str += child_str
comment_str += '</div>'
return comment_str
方式二:
前端生成页面加载完成之后发送ajax请求
js 函数递归
字符串格式化
$.ajax({
url:'/comment.html',
data:{'typename':{{ article.article.aid }},'csrfmiddlewaretoken':'{{ csrf_token }}'},
type:'post',
dataType:'JSON',
success:function (data) {
var comment=commentTree(data);
$('.commentarea').append(comment)
}
});
{# var nn =new Date;#}
{# nn.getDate() ;#}
/*
前端 调用对象方法时,是通过调用类的propotype中的方法
正则表达式:/\w+/g
字符串replace
''.replace(/(\w+)/g,function(k,kk){return 11})
*/
String.prototype.Format=function(arg){
/*
this 当前字符串
arg format方法传入的参数{key:value}
return 格式化之后获取的新内容
*/
var temp=this.replace(/\{(\w+)\}/g,function(k,kk){
return arg[kk];
});
return temp;
};
function commentTree(comment_list){
var comment_str="<div class='comment'>";
$.each(comment_list,function(k,row){
var temp="<div class='content'>{user}{content}---{time}</div>";
var temp1=temp.Format({user:row.user__nickname,content:row.content,time:row.create_time});
comment_str += temp1;
if(row.child.length>0){
comment_str += commentTree(row.child);
}
});
comment_str += "</div>";
return comment_str
}
多级评论在前端页面进行递归
class JsonCustomEncoder(json.JSONEncoder):
def default(self, field):
if isinstance(field, datetime):
return field.strftime('%Y-%m-%d %H:%M:%S');
elif isinstance(field, date):
return field.strftime('%Y-%m-%d');
else:
return json.JSONEncoder.default(self, field);
def commcnts(request,nid):
response={'status':True,'data':None,'mag':None}
print('is nid...',nid)
try:
comment_list=models.Comment.objects.filter(article_id=nid).values(
"nid", "reply_id", "user__nid",
"user__nickname", "create_time", "content",
"reply__user__nickname",
)
# 连表查询内容
comment_list_dict = {}
# 定一个空字典
for item in comment_list:
#循环连表获取到的内容
item['child'] = []
# 给循环的每一个字典添加一个空列表
comment_list_dict[item['nid']] = item
#给新创建的字典添加一对数据,键是循环的字典里的每一个id 值是循环的每一个字典
result = []
# 定一个空列表
for item in comment_list:
# 循环连表获取到的内容
pid = item['reply_id']
# 拿到每个字典reply_id键对应的值赋值给变量
if pid: # 如果pid为True
comment_list_dict[pid]['child'].append(item)
#刚刚判断回复的id有值,就把回复有值字典添加comment_lsit_dict字典的child键对应的列表中
else: # 为None
result.append(item) # result结果增加没有孩子的字典
response['data'] = result
# 重写response字典data的值,值更换为刚刚得到的新的字典
print('is result',result)
except Exception as e:
# 捕捉异常
response['status'] = False
# 如果有异常就重写response字典的status键对应的值,值更改为False
response['msg'] = str(e)
#如果有异常就重写response字典的msg键对应的值,值更改为捕捉到的异常信息
return HttpResponse(json.dumps(response, cls=JsonCustomEncoder))
# 返回一个字符串返回的有response的内容和一个类和对象
{#==================================定一个函数添加评论楼的信息============================#}
function commentTree(comment_list) {
{#定义一个函数,这个函数的参数 comment_list 是在被调用时( var comment = commentTree(arg.data);)arg.data传值过来的#}
var comment_str = "<div class=comment>";
{#定一个自变量,内容是字符串#}
$.each(comment_list, function (k,row) {
{#循环一下 comment_list 列表 分别拿到索引和参数,函数中只写一个的时候获取到的是索引值#}
{# var temp = "<div class='content'>" + row.content + "</div>";#}
console.log(comment_list);
var temp = "<div class='content'>{user}-{content}--{time}</div>";
{#定一个变量,内容是字符串但是有机个字符占位符#}
var temp1 = temp.Format({ user:row.user__nickname, content:row.content, time: row.create_time});
{#定一个一个变量接受刚刚定义的变量格式化的内容#}
comment_str += temp1;
{#每循环一次都把得到的内容添加到 comment_str 变量中#}
{# comment_str += temp;#}
if (row.child.length > 0) {
{#通过row.child 每次循环的字典中的孩子长度判断孩子存不存在#}
comment_str += commentTree(row.child)
{#孩子存在的就进行递归的查找和添加#}
}
});
comment_str += '</dic>';
{#在循环完以后在给变量设置一个div的结束标签#}
return comment_str
{#最后把得到字符串变量返回#}
}
多级评论在后端页面进行递归
comment_list = models.Comment.objects.filter(article_id=user_id).values(
"nid", "reply_id", "user__nid",
"user__nickname", "create_time", "content",
"reply__user__nickname"
)
print('is comment_list',comment_list)
comment_list_dict = {}
for item in comment_list:
item['child'] = []
comment_list_dict[item['nid']] = item
print(comment_list_dict)
result = []
for item in comment_list:
pid = item['reply_id']
if pid: # 如果pid为True
comment_list_dict[pid]['child'].append(item)
else: # 为None
result.append(item) # result结果增加item
from check.comment import comment_tree
comment_str = comment_tree(result)
caregory_list, tag_lsit, time_list, article_list, fen, guanzhu, users_list = fiflers(request, blog)
print('title,user_id',title,user_id)
xx=models.ArticleDetail.objects.filter(id=user_id)
print(xx)
return render(request,'xiangxi.html',{
'xx':xx,
'caregory_list': caregory_list,
'tag_lsit': tag_lsit,
'time_list': time_list,
'article_list': article_list,
'fen': fen,
'guanzhu': guanzhu,
'users_list': users_list,
'blog':blog,
'user_id':user_id,
"comment_str":comment_str
})

浙公网安备 33010602011771号