Search code examples
pythondjangolistviewdjango-querysetdjango-related-manager

Django: Get all objects from a specific user


I have a problem when trying to display all the Announce objects from a user. My problem is : Consider that I am logged in as a user with an id=1. When I go to /users/1/ it displays all my posts. But the problem is when I want to display all the posts from another user with id=2 by going to /users/2/, it still display all my Announce objects, and not the user with the id=2.

models.py

class Announce(models.Model):
    owner        = models.ForeignKey('auth.User', related_name='announces')
    created_date = models.DateTimeField(auto_now_add=True)
    body         = models.TextField(max_length=1000)

views.py

class UserAnnouncesList(ListView):
    model = Announce
    template_name = 'myApp/user_announces_list.html'
    context_object_name = 'all_announces_by_user'

    def get_queryset(self):
        return Announce.objects.filter(owner=self.request.user)

urls.py

urlpatterns = [
url(r'users/(?P<pk>[0-9]+)/$', views.UserAnnouncesList.as_view(), name='user_announces_list'),]

user_announces_list.html

{% extends "account/base.html" %}

{% block content %}
{% for announce in all_announces_by_user %}
<h1>{{announce.user.username}}</h1>
    <p>{{announce.body}}</p>

{% endfor %}
{% endblock content %}

Do I have to use some kind of like : Announce.objects.get(pk=???) ?

I appreciate your help!


Solution

  • The request.user is the user that is logged in. You need to use the pk that is passed as url. This is stored in the kwargs dictionary of the listview:

    class UserAnnouncesList(ListView):
        model = Announce
        template_name = 'myApp/user_announces_list.html'
        context_object_name = 'all_announces_by_user'
    
        def get_queryset(self):
            return Announce.objects.filter(owner=self.kwargs['pk'])