您当前的位置: 首页 >  django

IT之一小佬

暂无认证

  • 2浏览

    0关注

    1192博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Django博客系统(详情评论数据展示)

IT之一小佬 发布时间:2021-10-03 02:12:45 ,浏览量:2

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文件中使用模板语言展示分类数据


共有{{ total_count }}条评论
{% for comment in comments %}

{{ comment.user.username }} {{ comment.created | date:'Y:m:d H:i:s' }}

{{ comment.content|safe }}

{% endfor %}

3.修改底部js分页代码


    $(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;
            }
        })
    });

2. 插入更多测试数据

我们可以通过蠕虫复制来插入更多测试数据

insert into tb_comment(content,created,article_id,user_id)
select content,created,article_id,user_id from tb_comment;
关注
打赏
1665675218
查看更多评论
立即登录/注册

微信扫码登录

0.0940s