Posts tagged under django

30 Aug 2016

Building a Simple Search in Django

This is a brief tutorial on how to implement a simple text search on your Django site, for something like a blog, as I've implemented here at  

Step 1

The first piece we will write is the form itself, where users will enter their search term.  As seen in the HTML below, it is relatively simple.  We just have to tell it where to submit with the action attribute.  We will define this url in the following steps, although take note of the /blog/search portion after the {{ request.get_host }} tag.  In my case, I've set up my search as a part of my blog app.  Other than that, we just tell our button to submit the form by its id name when clicked, and it's all set.  

<form id="searchform" action="{{ request.get_host }}/blog/search/" method="get">
    <input type="text" name="q" type="text"/>
    <button type="button" onclick="searchform.submit()">Search</button>

Step 2

I will mention again, I've included the search within my blog app.  To use this example, you want to be working in the same app as the models you're trying to search, and the views that will display the results.  Add the following line to your app's file under the urlpatterns list in your app:

url(r'^search/',, name="search")

Step 3

Now that the request is being directed to the correct view, let's create the view.  We will create a search function to retrieve ...