多级评论
1。普通多级评论:
a.图解


b.建立数据库评论表:
class Comment(models.Model): """ 评论表 """ nid = models.BigAutoField(primary_key=True) content = models.CharField(verbose_name='评论内容', max_length=255) create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True) reply = models.ForeignKey(verbose_name='回复评论', to='self', related_name='back', null=True) article = models.ForeignKey(verbose_name='评论文章', to='Article', to_field='nid') user = models.ForeignKey(verbose_name='评论者', to='UserInfo', to_field='nid')
c.评论:从数据库取值(建立urls.py,然后写入views.py)
#评论:从数据库取值(写入views.py)
def info(request):
if request.method == "GET":
msg_list = models.Comment.objects.filter(article_id=nid).values("nid","reply_id","user__nid","user__nickname","create_time","content","reply__user__nickname")
##################################
msg_list_dict = {}
for item in msg_list:
item['child'] = []
msg_list_dict[item['nid']] = item
###### msg_list_dict用于查找,msg_list#####
result = []
for item in msg_list:
pid = item['reply_id']
if pid:
msg_list_dict[pid]['child'].append(item)
else:
result.append(item)
#导入模块
from utils.comment import comment_tree
comment_str = comment_tree(result)
#####################################
return render(request, 'index_article_list.html', {
'comment_str': comment_str,
})
utils:(comment.py导入views中)
def comment_tree(comment_list): """ :param result: [ {id,:child:[xxx]},{}] :return: """ comment_str = "<div class='comment'>" for row in comment_list: tpl = "<div class='content'>%s</div>" %(row['content']) comment_str += tpl if row['child']: child_str = comment_tree(row['child']) comment_str += child_str comment_str += "</div>" return comment_str
d.前端页面取值(建立html):
{{ comment_str|safe }}
############################################################

浙公网安备 33010602011771号