[Django]-Pass url argument to ListView queryset

40👍

You need to write your own view for that and then just override the get_queryset method:

class CustomListView(ListView):
    def get_queryset(self):
        return Message.objects.filter(lab__acronym=self.kwargs['lab'])

and use CustomListView in urls also.

5👍

class CustomListView(ListView):
    model = Message
    
    def get(self, request, *args, **kwargs):
        # either
        self.object_list = self.get_queryset()
        self.object_list = self.object_list.filter(lab__acronym=kwargs['lab'])
         
        # or
        queryset = Lab.objects.filter(acronym=kwargs['lab'])
        if queryset.exists():
            self.object_list = self.object_list.filter(lab__acronym=kwargs['lab'])
        else:
            raise Http404("No lab found for this acronym")

        # in both cases
        context = self.get_context_data()
        return self.render_to_response(context)

Leave a comment