简体   繁体   English

如何在Django中计算博客类别并将其显示在模板中

[英]How to count blog categories in django and display them in a template

am new in django am developing a blog which has functions post_list,category_detail and post detail am stuck in post_list function which renders a blog.html i want to display the blog category which are python and hardware together with the total number of posts in that category i have tried my ways it shows the wrong way since there should be six posts in python category and one post in hardware category see the picture here please check the codes and help out django的新用户正在开发具有功能post_list,category_detail和post detail的博客,将其粘贴在post_list函数中,该函数将呈现一个blog.html。我想显示博客类别,包括python和硬件以及该类别中帖子的总数我已经尝试了显示错误方式的方法,因为在python类别中应该有6个帖子,在硬件类别中应该有1个帖子, 请参阅此处的图片,请检查代码并提供帮助

views.py views.py

 def post_list(request): object_list=Post.objects.filter(status='Published').order_by("-created") recent_post=object_list[:4] category_list_count=Post.objects.annotate(num_category=Count('Category')) page = request.GET.get('page', 1) paginator = Paginator(object_list, 3) try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) context={ 'items':items, 'recent_post':recent_post, 'category_list_count':category_list_count, } return render(request,"blog.html",context) 

blog.html blog.html

  <div class="widget"> <h3 class="badge">CATEGORIES</h3> {% for obj in category_list_count %} <ul> <li><a href="{% url 'category_detail' slug=obj.Category.slug %}">{{obj.Category}}</a> <span class="badge">{{obj.num_category}}</span> </li> </ul> {% endfor %} 

Try this: 尝试这个:

# You should change post in Count function based on your model.
categories = Category.objects.all().annotate(posts_count=Count('post'))

Then you will have access to number of posts for each category: 然后,您将可以访问每个类别的帖子数量:

for category in categories:
    print(category.posts_count)

In your template: 在您的模板中:

{% for category in categories %}
      <p>Number of posts: {{category.posts_count}}</p>
{% endfor %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM