1. 查询评论数据并展示
1.查询评论数据并通过context传递给HTML
from home.models import Comment
from django.shortcuts import redirect,reverse
class DetailView(View):
def get(self,request):
# detail/?id=xxx&page_num=xxx&page_size=xxx
#获取文档id
id=request.GET.get('id')
page_num=request.GET.get('page_num',1)
page_size=request.GET.get('page_size',5)
# 获取博客分类信息
categories = ArticleCategory.objects.all()
try:
article=Article.objects.get(id=id)
except Article.DoesNotExist:
return render(request,'404.html')
else:
article.total_views+=1
article.save()
# 获取热点数据
hot_articles = Article.objects.order_by('-total_views')[:9]
# 获取当前文章的评论数据
comments = Comment.objects.filter(
article=article
).order_by('-created')
#获取评论总数
total_count = comments.count()
# 创建分页器:每页N条记录
paginator = Paginator(comments, page_size)
# 获取每页商品数据
try:
page_comments = paginator.page(page_num)
except EmptyPage:
# 如果page_num不正确,默认给用户404
return HttpResponseNotFound('empty page')
# 获取列表页总页数
total_page = paginator.num_pages
context = {
'categories':categories,
'category':article.category,
'article':article,
'hot_articles':hot_articles,
'total_count': total_count,
'comments': page_comments,
'page_size': page_size,
'total_page': total_page,
'page_num': page_num,
}
return render(request,'detail.html',context=context)
2.在index.html文件中使用模板语言展示分类数据
<!-- 显示评论 -->
<h4>共有{{ total_count }}条评论</h4>
<div class="row">
{% for comment in comments %}
<div class="col-12" >
<hr><p><strong style="color: pink"></strong></p>
<div>
<div><span><strong>{{ comment.user.username }}</strong></span> <span style="color: gray">{{ comment.created | date:'Y:m:d H:i:s' }}</span></div>
<br>
<p>{{ comment.content|safe }}</p>
</div>
</div>
{% endfor %}
<div class="pagenation" style="text-align: center">
<div id="pagination" class="page"></div>
</div>
</div>
3.修改底部js分页代码
<script type="text/javascript">
$(function () {
$('#pagination').pagination({
currentPage: {{ page_num }},
totalPage: {{ total_page }},
callback:function (current) {
location.href = '/detail/?id={{ article.id }}&page_size={{ page_size }}&page_num='+current;
}
})
});
</script>
2. 插入更多测试数据
我们可以通过蠕虫复制来插入更多测试数据
insert into tb_comment(content,created,article_id,user_id)
select content,created,article_id,user_id from tb_comment;