Django Tutorial, Part II

Today we’re going to implement search functionality in our song app. This will include basic form processing in our view, and returning search results to the client. Ready? Let’s get started!

1. Add an entry in urls for your search method.
Open up in a text editor, then enter the following under your list entry:


This says that any url ‘search’ will be mapped to the search method in

2. Create the search form in your site’s templates directory.
Open up in a text editor, and find the TEMPLATE_DIRS section, then enter a full path to your templates, preferably somewhere in your project’s path. Then, create the directory per the setting you entered. In this directory, create a file called search.html and enter the following code:

<form id="search_form" action="." method="get">
	<input type="text" name="q" id="q"/>
	<input type="submit" id="search-submit" value="Search"/>

{% if show_results %}
	{% if errors %}
		<ul class="errorlist">
			{% for error in errors %}
			<li>{{ error }}</li>
			{% endfor %}
	{% else %}
		<p>You searched for: <strong>{{ query }}</strong></p>
		{% if results %}
			<p> Found {{ results|length }} result{{ results|pluralize }}.</p>
				{% for result in results %}
					<li>{{ result.title|escape }} - {{ result.artist|escape }}</li>
				{% endfor %}
		{% else %}
			<p>No results found.</p>
		{% endif %}
	{% endif %}
{% endif %}

Here, the query is appended to the url as a search string.

3. Create a search method in
In your search method, check if query string is part of the GET request and get from the db:

def search(request):
	if 'q' in request.GET:
		errors = []
		query = request.GET['q'].strip()
		if not query:
			errors.append('Enter a search term.')
			show_results = True
			results = Song.objects.filter(title__icontains=query)
			variables = RequestContext(request,
					'results' : results,
					'show_results' : show_results,
					'query' : query,
					'errors' : errors
			return render_to_response('search.html', variables)
	return render_to_response('search.html');

You should now be able to start up the server with python runserver, and navigate to http://localhost:8000/search to see your search form. Enter the title of one of your songs, and you should be able to submit the form and see the search results.
That’s it for now! Next time, we’ll work on some adding new songs.


About buffalobillion

Web Developer, JavaScript Balrog, Java dude, Ruby/Rails enthusiast. Guitar Playa.
This entry was posted in Web Dev. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s