Writing a search view with Django
While working on the latest incarnation of my website, I decided that it was time that I figured out how to enable searching of my website. Ever since I converted my site from Wordpress, searching my site hasn’t been possible, unless using a search engine and limiting it only to my domain. This was less than agreeable with me since it seems like something that could be written in Django, especially since the admin interface already has a search that works.
After scouring the web looking for some code to help me along the path, I eventually came across this post on Petro Verkhogliad’s blog. Using Petro’s code as a starting point, I was able to work out something of my own, which is a bit simpler, and feels more… Django-ish. Below is the code that I’m using for my current implementation of search. It returns two variables to the template results and query.
results is a list object with references to all the blog postings that match your query. query is a simple reference to your search terms, which is useful for pre-populating search forms, or inserting the terms into a header or other text area.
from django.http import HttpResponse from django.shortcuts import render_to_response, get_object_or_404 from django.db.models import Q from wolfsreign.apps.blog.models import Postdef search(request): query = request.GET.get("s", "") q = Q() for term in query.split( ):results = Post.objects.filter(Q(status="Published"), Q(title__icontains=term) | Q(body__icontains=term)) results = list(results)q |= Q(title__icontains=term) | Q(body__icontains=term) results = Post.objects.filter(Q(status="Published"), q) return render_to_response("search/results.html", {"results": results,"query": query})
This view sends the context to the results template, which might looks like this:
<h1>Search results for {{ query }}</h1>
<ul>
{% for result in results %}
<li><a href="{{ results.get_absolute_url }}">{{ results.title }}</a></li>
{% endfor %}
</ul>
Hopefully this helps some of you, like it’s helped me.
As Sago points out, my original code was not using all of the search terms that were being provided. It was only searching based on the last word in the search. I have updated the code to reflect his suggested changes. If you have been using my older code, you might find it beneficial to update your code.
Nine Comments
Jump to comment form