Searching Snippets

In this lesson, we will add a view to allow users to search snippets via keywords.

Let’s start by creating a search form.

In the, define SearchForm class towards the end of the file as follows:


The query field is where the users will enter their search term. The mysnippet field will be visible only to the users who are logged in. If selected, it allows users to search through his snippets only.

Next, add a new view named search() in just below the profile() view as follows:


This view function works as follows:

  1. In line 9, we instantiate a SearchForm instance by passing request.GET data to form constructor. The reason we are binding data to the form at the outset is that the search() function will be will be called only when the user has submitted the query in the search box at the top of the page. Further, the query is submitted using the GET request this allows users to bookmark the search if they want to.
  2. In line 12, we use is_valid() method to determine whether the form is valid or not. If the form is not valid, we render an empty form without any data; otherwise, the course of action depends upon how the form is submitted. There are two possible scenarios:

If the form is submitted with mysnippet field checked, then this will trigger the execution of the following if block.

On the other hand, If the form is submitted without the mysnippet field checked, then this will trigger the execution of the else block.

If the user is logged in, we create a new queryset containing the snippets created by the user. The querysets qs1 and qs2 may contain duplicate results. To remove the duplicates combine two querysets using | (bitwise OR) operator and then apply the distinct() method on the resulting queryset. We are now left with unique results.

In line 40, we call paginate_result() to get paginated results.

Finally, in line 42, we render the template.

Add a URL pattern named search to as follows:


Create a template named search.html and add the following code to it:


Next, update <form> element base.html as follows:

Now, open your browser and navigate to http://localhost:8000/. Enter a query in the search box at the top of the page and hit enter. You should see search results as follows:

If you are logged in then you will see mysnippet select box beside the search box as follows:

Submitting the form with mysnippet field checked will limit the search results to your snippets only.

1 thought on “Searching Snippets

  1. All the articles on Django in this website (OverIQ) are very clearly explained and easy to understand. I have gained very good knowledge on Django by going through these topics. Thank you once again.

    I am searching for “Django AJAX Search Autocomplete”. i.e just like we see in Goggle search. After typing a character we get the drop down of suggested words. Can you please suggest me the code or link please

Leave a Comment

%d bloggers like this: