Reputation: 21
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...
Upvotes: 1
Views: 756
Reputation: 477804
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 }}
Upvotes: 1