Skip to content
Advertisement

How to get object_list of another user using ListView in Django?

I am new to Django and I am creating a simple blog web application. I would like to get the blog post of another user (not the user that is Authenticated) using the get_queryset Method. I tried the script below but, it shows an empty list on the template. I am able to use get_queryset to show all the blogpost, but my main concern is to show all the blogpost of a specific user (not the user that is authenticated)

View.py

class OtherUserProfileView(LoginRequiredMixin, ListView):

model = Post
template_name = "core/otheruser.html"

def get_queryset(self):
    queryset = super(OtherUserProfileView, self).get_queryset()
    queryset = queryset.filter(pk=self.user.id)
    return queryset

Model.py

class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=250)
content = models.TextField()
created = models.DateTimeField(auto_now_add=True)
publish = models.BooleanField(blank=True, default=False)

def __str__(self):
    return self.title

Advertisement

Answer

You can pass the id of the user that you want to filter the queryset by in the url pattern

urlpatterns = [
    path('profile/<int:user_id>/', views.OtherUserProfileView.as_view(), name='profile'),
]

In your view you can access the user_id from the path via self.kwargs['user_id'] and use this to filter your queryset

class OtherUserProfileView(LoginRequiredMixin, ListView):

    model = Post
    template_name = "core/otheruser.html"

    def get_queryset(self):
        queryset = super().get_queryset()
        queryset = queryset.filter(user_id=self.kwargs['user_id'])
        return queryset
Advertisement