1

Can anyone please tell me how I can pass the "query" on my ListView as a context while at the same time keeping "search_results" as a context_object_name? I just can't get my head around it:

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

    def get_queryset(self):
        query = self.request.GET.get("q")
        search_results = Product.objects.filter(
            Q(name__icontains=query)
            )
        return search_results

Am trying to render the values passed to "query" on my template but I just can't figure out how...

Monk BR
  • 21
  • 3

1 Answers1

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 }}
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555