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
JavaScript
x
10
10
1
class OtherUserProfileView(LoginRequiredMixin, ListView):
2
3
model = Post
4
template_name = "core/otheruser.html"
5
6
def get_queryset(self):
7
queryset = super(OtherUserProfileView, self).get_queryset()
8
queryset = queryset.filter(pk=self.user.id)
9
return queryset
10
Model.py
JavaScript
1
10
10
1
class Post(models.Model):
2
user = models.ForeignKey(User, on_delete=models.CASCADE)
3
title = models.CharField(max_length=250)
4
content = models.TextField()
5
created = models.DateTimeField(auto_now_add=True)
6
publish = models.BooleanField(blank=True, default=False)
7
8
def __str__(self):
9
return self.title
10
Advertisement
Answer
You can pass the id of the user that you want to filter the queryset by in the url pattern
JavaScript
1
4
1
urlpatterns = [
2
path('profile/<int:user_id>/', views.OtherUserProfileView.as_view(), name='profile'),
3
]
4
In your view you can access the user_id
from the path via self.kwargs['user_id']
and use this to filter your queryset
JavaScript
1
10
10
1
class OtherUserProfileView(LoginRequiredMixin, ListView):
2
3
model = Post
4
template_name = "core/otheruser.html"
5
6
def get_queryset(self):
7
queryset = super().get_queryset()
8
queryset = queryset.filter(user_id=self.kwargs['user_id'])
9
return queryset
10