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












0















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



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






      <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 %}












share|improve this question



























    0















    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



    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






          <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 %}












    share|improve this question

























      0












      0








      0








      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



      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






            <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 %}












      share|improve this question














      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



      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






            <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 %}








      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)





      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)





            <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 %}





            <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 %}






      javascript python html django






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 25 '18 at 14:04









      CipherCipher

      46




      46
























          1 Answer
          1






          active

          oldest

          votes


















          0














          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 %}





          share|improve this answer
























          • Am getting an error NoReverseMatch at /blog/ Reverse for 'category_detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['blog\/category\-detail\/(?P<slug>[-a-zA-Z0-9_]+)$']

            – Cipher
            Nov 25 '18 at 16:22











          • Thank you worked i had to change the url from {% url 'category_detail' slug=obj.Category.slug %} to {% url 'category_detail' category.slug %}

            – Cipher
            Nov 25 '18 at 16:38











          • Just one thing cant figure out is this <li><a href="{% url 'category_detail' category.slug %}">{{category}}</a> <span class="badge">{{category.post_count}}</span> as you can see the picture i attached it has to be category and the badge count of posts please help out

            – Cipher
            Nov 25 '18 at 16:42











          • Whats the problem? it should work

            – Navid2zp
            Nov 25 '18 at 16:56











          • yeah it worked thanks

            – Cipher
            Nov 26 '18 at 11:33











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53468286%2fhow-to-count-blog-categories-in-django-and-display-them-in-a-template%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          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 %}





          share|improve this answer
























          • Am getting an error NoReverseMatch at /blog/ Reverse for 'category_detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['blog\/category\-detail\/(?P<slug>[-a-zA-Z0-9_]+)$']

            – Cipher
            Nov 25 '18 at 16:22











          • Thank you worked i had to change the url from {% url 'category_detail' slug=obj.Category.slug %} to {% url 'category_detail' category.slug %}

            – Cipher
            Nov 25 '18 at 16:38











          • Just one thing cant figure out is this <li><a href="{% url 'category_detail' category.slug %}">{{category}}</a> <span class="badge">{{category.post_count}}</span> as you can see the picture i attached it has to be category and the badge count of posts please help out

            – Cipher
            Nov 25 '18 at 16:42











          • Whats the problem? it should work

            – Navid2zp
            Nov 25 '18 at 16:56











          • yeah it worked thanks

            – Cipher
            Nov 26 '18 at 11:33
















          0














          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 %}





          share|improve this answer
























          • Am getting an error NoReverseMatch at /blog/ Reverse for 'category_detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['blog\/category\-detail\/(?P<slug>[-a-zA-Z0-9_]+)$']

            – Cipher
            Nov 25 '18 at 16:22











          • Thank you worked i had to change the url from {% url 'category_detail' slug=obj.Category.slug %} to {% url 'category_detail' category.slug %}

            – Cipher
            Nov 25 '18 at 16:38











          • Just one thing cant figure out is this <li><a href="{% url 'category_detail' category.slug %}">{{category}}</a> <span class="badge">{{category.post_count}}</span> as you can see the picture i attached it has to be category and the badge count of posts please help out

            – Cipher
            Nov 25 '18 at 16:42











          • Whats the problem? it should work

            – Navid2zp
            Nov 25 '18 at 16:56











          • yeah it worked thanks

            – Cipher
            Nov 26 '18 at 11:33














          0












          0








          0







          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 %}





          share|improve this answer













          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 %}






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 25 '18 at 16:04









          Navid2zpNavid2zp

          1,278518




          1,278518













          • Am getting an error NoReverseMatch at /blog/ Reverse for 'category_detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['blog\/category\-detail\/(?P<slug>[-a-zA-Z0-9_]+)$']

            – Cipher
            Nov 25 '18 at 16:22











          • Thank you worked i had to change the url from {% url 'category_detail' slug=obj.Category.slug %} to {% url 'category_detail' category.slug %}

            – Cipher
            Nov 25 '18 at 16:38











          • Just one thing cant figure out is this <li><a href="{% url 'category_detail' category.slug %}">{{category}}</a> <span class="badge">{{category.post_count}}</span> as you can see the picture i attached it has to be category and the badge count of posts please help out

            – Cipher
            Nov 25 '18 at 16:42











          • Whats the problem? it should work

            – Navid2zp
            Nov 25 '18 at 16:56











          • yeah it worked thanks

            – Cipher
            Nov 26 '18 at 11:33



















          • Am getting an error NoReverseMatch at /blog/ Reverse for 'category_detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['blog\/category\-detail\/(?P<slug>[-a-zA-Z0-9_]+)$']

            – Cipher
            Nov 25 '18 at 16:22











          • Thank you worked i had to change the url from {% url 'category_detail' slug=obj.Category.slug %} to {% url 'category_detail' category.slug %}

            – Cipher
            Nov 25 '18 at 16:38











          • Just one thing cant figure out is this <li><a href="{% url 'category_detail' category.slug %}">{{category}}</a> <span class="badge">{{category.post_count}}</span> as you can see the picture i attached it has to be category and the badge count of posts please help out

            – Cipher
            Nov 25 '18 at 16:42











          • Whats the problem? it should work

            – Navid2zp
            Nov 25 '18 at 16:56











          • yeah it worked thanks

            – Cipher
            Nov 26 '18 at 11:33

















          Am getting an error NoReverseMatch at /blog/ Reverse for 'category_detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['blog\/category\-detail\/(?P<slug>[-a-zA-Z0-9_]+)$']

          – Cipher
          Nov 25 '18 at 16:22





          Am getting an error NoReverseMatch at /blog/ Reverse for 'category_detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['blog\/category\-detail\/(?P<slug>[-a-zA-Z0-9_]+)$']

          – Cipher
          Nov 25 '18 at 16:22













          Thank you worked i had to change the url from {% url 'category_detail' slug=obj.Category.slug %} to {% url 'category_detail' category.slug %}

          – Cipher
          Nov 25 '18 at 16:38





          Thank you worked i had to change the url from {% url 'category_detail' slug=obj.Category.slug %} to {% url 'category_detail' category.slug %}

          – Cipher
          Nov 25 '18 at 16:38













          Just one thing cant figure out is this <li><a href="{% url 'category_detail' category.slug %}">{{category}}</a> <span class="badge">{{category.post_count}}</span> as you can see the picture i attached it has to be category and the badge count of posts please help out

          – Cipher
          Nov 25 '18 at 16:42





          Just one thing cant figure out is this <li><a href="{% url 'category_detail' category.slug %}">{{category}}</a> <span class="badge">{{category.post_count}}</span> as you can see the picture i attached it has to be category and the badge count of posts please help out

          – Cipher
          Nov 25 '18 at 16:42













          Whats the problem? it should work

          – Navid2zp
          Nov 25 '18 at 16:56





          Whats the problem? it should work

          – Navid2zp
          Nov 25 '18 at 16:56













          yeah it worked thanks

          – Cipher
          Nov 26 '18 at 11:33





          yeah it worked thanks

          – Cipher
          Nov 26 '18 at 11:33




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53468286%2fhow-to-count-blog-categories-in-django-and-display-them-in-a-template%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Wiesbaden

          Marschland

          Dieringhausen