Friday, December 22, 2017

Re: Search results in template

Thanks to both of you. The template context is what it should be, and putting all the view in the same block made no difference. :-(

On Wednesday, December 20, 2017 at 6:24:57 AM UTC-8, James Schneider wrote:

On Dec 19, 2017 5:12 PM, "Malik Rumi" <> wrote:

I am implementing search on a local Django project: Django 1.11.5, Python 3.6.3, Ubuntu 16.04. My issue is getting the search results onto the template.

I am using standard CBV for everything else in the site, but for this one I wrote my own. It uses the same template as my ListView, which shows all objects fine.

def serp(request):      if request.method == 'GET' and 'searchbox' in request.GET:          q = request.GET.get('searchbox')      query = SearchQuery(q)      object_list = Entry.objects.annotate(          rank=SearchRank(F(              'search_vector'), query)).filter(          search_vector=query).order_by(          '-rank').values_list('title', 'rank')      return render(request, 'serp_list.html', {'object_list': object_list})

Django Debug Toolbar reports everything went as expected. The right template and view were called, as well as the right db query. I had previously tested this query in the shell, and it pulls up a 4 element queryset, as it should. 

Your view has a bug. If the first 'if' statement returns false, then the view fails because the 'q' variable is never set, and your viewer will get a 500 error. I think the two lines following the 'q =' line should be indented inside of the if statement, and object_list should be set to an empty list by default before the 'if' statement.

You should also ensure that this view is the one that is actually being called by the URL dispatcher.

Checking what is in the template context with the DDT is the next step. If the template context is incorrect, then you'll need to debug within your view to determine where/why the context is not being set correctly.

'object_list' is a generic variable name used by list CBV's in the template context, but should be available to FBV's since there is no magic context creation.


You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
To post to this group, send email to
Visit this group at
To view this discussion on the web visit
For more options, visit

No comments:

Post a Comment