Home > Net >  count the number of posts
count the number of posts

Time:11-23

I have created a website and want to count user generated posts. I tried to do it as follows:

models.py
class Blog(models.Model):
    user = models.ForeignKey(
        User,
        related_name='user_blogs',
        on_delete=models.CASCADE
    )
    category = models.ForeignKey(
        Category,
        related_name='category_blogs',
        on_delete=models.CASCADE
    )

    title = models.CharField(
        max_length=250
    )
    slug = models.SlugField(null=True, blank=True)


    banner = models.ImageField(upload_to='blog_banners')
    description = RichTextField()
    created_date = models.DateField(auto_now_add=True)

    def __str__(self) -> str:
        return self.title

    def save(self, *args, **kwargs):
        updating = self.pk is not None
        
        if updating:
            self.slug = generate_unique_slug(self, self.title, update=True)
            super().save(*args, **kwargs)
        else:
            self.slug = generate_unique_slug(self, self.title)
            super().save(*args, **kwargs)

templates

<span>Posts: <strong>{{account.user_blogs.count}}</strong></span>

but it doesn't work what is the problem? should I rewrite the code at all?

CodePudding user response:

You can use .count() in view to count all the posts of request.user like -

def some_view(request):
    count_posts = Blog.objects.filter(user=request.user).count()

    context = {"count_posts": count_posts}
    return render(request, 'template.html', context)

template.html

{{count_posts}}

CodePudding user response:

If you're trying to count posts created by the logged-in user

<span>Posts: <strong>{{ request.user.user_blogs.count }}</strong></span>
  • Related