Search code examples
pythondjangodjango-haystack

Django display search keyword and count in template


How to display the actual keyword and count in custom search form?

My Haystack custom search is working just fine but I'm having difficulties displaying the actual keyword and count.

When I was using the default Haystack urls the {{ query }} would display the actual keyword.

When using custom search form the {{ query }} and {{ query.count }} is empty.

form.py

class BusinessSearchForm(SearchForm):

def no_query_found(self):
    return self.searchqueryset.all()

def search(self):
    sqs = super(BusinessSearchForm, self).search()

    if not self.is_valid():
        return self.no_query_found()

    return sqs

view.py

def business_search(request):
form = BusinessSearchForm(request.GET)
businesslist = form.search()
paginator = Paginator(businesslist, 5) 
page = request.GET.get('page')
try:
    businesslist = paginator.page(page)
except PageNotAnInteger:
    businesslist = paginator.page(1)
except EmptyPage:
    businesslist = paginator.page(paginator.num_pages)

return render_to_response('businesslist.html', {'businesslist': businesslist},
                            context_instance=RequestContext(request))

template.html

Your query {{ query }} has returned {{ query.count }} result{{ businesslist|pluralize }}

Solution

  • You'll need to pass on query as context.

    So something like this:

    context = {
        'query': form.cleaned_data['q'],
        'businesslist': businesslist,
        'paginator': paginator,
    }
    
    return render_to_response('businesslist.html', context, context_instance=RequestContext(request))
    

    And you can use paginator.count to get number of results.

    template.html

    Your query {{ query }} has returned {{ paginator.count }} result{{ paginator.count|pluralize }}.