Sugata Kar
Sugata Kar

Reputation: 377

How to diplay number of blog posted per category in Django

I am developing a blog website using Django and trying to display the no. of the post made per category on the homepage.

models.py:

class Category(models.Model):

    CATEGORY = (
        ("Un-categorized", "Un-categorized"),
        ("Machine Learning", "Machine Learning"),
        ("Data Science", "Data Science"),
        ("Programming", "Programming"),
        ("Latest Trends", "Latest Trends")
    )

    category = models.CharField(max_length=20, choices=CATEGORY, default='Un-Categorized',unique=True)

    def __str__(self):
        return self.category

class Post(models.Model):

    title = models.CharField(max_length=20) # title of the post
    content = models.TextField()  # content of the post
    date_posted = models.DateTimeField(auto_now_add=True)  # when the post is created
    date_modified = models.DateTimeField(auto_now=True) # will store the date every time the post is updated and saved.
    author = models.ForeignKey(User, on_delete=models.CASCADE)  # Referring the django's inbuilt User model.
    category = models.ForeignKey(Category, on_delete=models.CASCADE)  # one post can have only one category whereas under one category there can be multiple post.
    img = models.ImageField(default='default.jpg', upload_to='post')
    # tag = to store important tags related to the post

    def __str__(self):
        return self.title

views.py :

def home(request): # Home page of the website.
    post = Post.objects.all().order_by('-date_posted') # To display all the post in desc order.
    categories = Category.objects.all()

    '''categories_count = []
    i = 1
    for item in categories.count():
        categories_count[item] = Categories.objects.filter(id=i).count()
        i += 1
    '''
    context = {
        'posts':post,
        # 'count' : categories_count,
        'categories': categories,
        # 'categories_count': categories_count
    }

    return render(request,'post/home.html',context=context)

.html file:

<div class="widget widget_categories group">
    <h3>Categories</h3> 
        <ul>
            {% for category in categories %}
            <li>
                <a href="{% url 'post-category' category.category %}" title="">
                    {{ category }}
                </a> 
                (<!--count of post made per category-->>)
            </li>   
            {% endfor %}                
        </ul>
</div>

I tried to implement this in my view but I couldn't able to complete it. I am not sure how to access the categories_count list under the context dic. from the template.

Upvotes: 0

Views: 732

Answers (2)

ImustAdmit
ImustAdmit

Reputation: 507

You can add 'post_count' = posts.count() to context dict in view. Then just use it in html {{ post_count }}

Upvotes: 1

Related Questions