Search code examples
pythondjangodjango-urlsdjango-generic-views

List of current user objects in Django ListView


I want to render list of all objects on my template, for which their author is the currently logged in user. I passed the username of current user to url.py:

<a href="{% url 'myscenarios' user.username %}">My List</a>

My urls.py:

path('myscenarios/<str:username>/', MyScenarioListView.as_view(), name='myscenarios'),

My question is how to build the queryset in views.py and what to type in template block in my html?

class MyScenarioListView(LoginRequiredMixin, ListView):
    model = Scenario
    template_name = 'testmanager/myscenarios.html'
    context_object_name = 'myscenarios'
    
    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Scenario.objects.filter(scenarioAuthor = user).order_by('-date_posted')

What code should I type in my myscenarios.html file?


Solution

  • I want to render list of all objects on my template, which their author is current logged user.

    Then you should not encode the user in the path, since a "hacker" can then simply change the URL to see the items belonging to a different user.

    You can make use of self.request.user here. The path thus looks like:

    path('myscenarios/', MyScenarioListView.as_view(), name='myscenarios'),

    and in the view, we use:

    class MyScenarioListView(LoginRequiredMixin, ListView):
        model = Scenario
        template_name = 'testmanager/myscenarios.html'
        context_object_name = 'myscenarios'
    
        def get_queryset(self):
            return Scenario.objects.filter(
                scenarioAuthor=self.request.user
            ).order_by('-date_posted')

    It will pass the Scenarios as myscenarios to the template, so you can render this with:

    {% for scenario in myscenarios %}
         {{ scenario }}
    {% endfor %}