Warm tip: This article is reproduced from serverfault.com, please click

How to get data of Post.user not the logged in User

发布于 2020-11-28 03:32:54

I am currently working on a blog project for learning purposes, I am trying to get the total number of posts made by a specific user. In my model I have set the User who makes a Post as Author.

In the Post detail page I am trying to show the total number of Posts made by this specific author but I am getting the data of the logged in User who is viewing the page.

The reason for this is using self in the get context data but I am not sure how to fix it so I need some explanation on how to amend this error in code.

Here is the Post Model:

class Post(models.Model):
    title = models.CharField(max_length=100, unique=True)
    content = RichTextUploadingField(null=True, blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author')

Here is the views.py:

class PostDetailView(DetailView):
    model = Post
    template_name = "blog/post_detail.html"  

    def get_context_data(self, *args, **kwargs):
        context = super(PostDetailView, self).get_context_data()
        post = get_object_or_404(Post, slug=self.kwargs['slug'])

        num_post = Post.objects.filter(author=self.request.user).count()#<--- No. of Posts made by an author

        context["num_post"] = num_post #<--- No. of Posts made by a user

        return context

My question: How to show the data of the post detail author not the logged in user

Thank you

Questioner
A_K
Viewed
0
ha-neul 2020-11-28 11:45:01

replace

num_post = Post.objects.filter(author=self.request.user).count()

with:

num_post = Post.objects.filter(author=post.author).count()