Django博客功能实现—文章评论的显示

功能:
在打开文章之后,能在文章下面是显示文章的评论,有父级评论。
思路:
在文章详情的视图里面,获取这个文章的全部评论,得到显示列表,然后用模板显示出来。
步骤:
一,在views.py的文章详情中获取评论:

 1 #文章详情
 2 #blog/views.py
 3 def article(request):
 4     try: 
 5         # 获取评论信息
 6         #查询指定文章的所有评论,按照id排序
 7         comments = Comment.objects.filter(article=article).order_by('id')
 8         #创建一个评论的空列表
 9         comment_list = []
10         #遍历一篇文章中的所有评论
11         for comment in comments:
12             for item in comment_list: 13 #判断item中是否有"children_comment"属性,返回布尔值 14 if not hasattr(item, 'children_comment'): 15 #若无"children_comment"属性,则设置这个属性,属性的值为[] 16 setattr(item, 'children_comment', []) 17 #如果item和父级评论的值相等,则讲该遍历出来的文章添加到"children_comment"属性,然后跳出当前循环 18 if comment.pid == item: 19  item.children_comment.append(comment) 20 break 21 #如果父级评论为空,则讲给评论放到父级评论列表里面 22 if comment.pid is None: 23  comment_list.append(comment) 24 except Exception as e: 25 print e 26  logger.error(e) 27 return render(request, 'article.html', locals())

二、在模板中显示出来

 1 #article.html
 2           {% for comment in comment_list %}
 3        
 4         <a href='{{ comment.url }}'>{{ comment.username }}</a><a href="#comment-59418">{{ comment.date_publish | date:'Y-m-d H:i:s' }}</a>
 5                 <div><img alt='' src='{% static 'images/default.jpg' %}' class='avatar avatar-32 photo' height='32' width='32' /></div>
 6 
 7                                 <p>{{ comment.content }}</p>
 8                 </div>
 9           </li>
10           {% for children_comment in comment.children_comment %}
11           <li id="comment-59542">
12                 <div class="reply">
13                   <div class="top"><a href="{{ children_comment.url }}" rel="external nofollow" class="url">{{ children_comment.username }}</a><span class="time"> @ <a href="#comment-59543" title="">{{ children_comment.date_publish | date:'Y-m-d H:i:s' }}</a></span></div>
14                   <div><img alt="" src="{% static 'images/default.jpg' %}" class="avatar avatar-32 photo" height="32" width="32"></div>
15 
16                   <div class="body">
17                                         {{ children_comment.content }}                  </div>
18                 </div>
19           </li>
20           {% endfor %}

 

如此就能讲一个文章的评论显示出来

转载于:https://www.cnblogs.com/cenyu/p/5713387.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值