[Answered ]-Passing Extra context to ListViews in Django

1👍

You can pass this by overriding the .get_context_data(…) method [Django-doc]:

class SearchResulView(ListView):
    model = Product
    template_name = 'shop/product/search_results.html'
    context_object_name = 'search_results' 

    def get_queryset(self):
        return super().get_queryset().filter(
            name__icontains=self.request.GET.get('q')
        )

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['query'] = self.request.GET.get('q')
        return context

You however do not need to override the .get_context_data(…) method. In the template you can access this with:

{{ view.request.GET.q }}

Leave a comment