Skip to content

Instantly share code, notes, and snippets.

@walesmd
Created October 16, 2009 16:33
Show Gist options
  • Save walesmd/211883 to your computer and use it in GitHub Desktop.
Save walesmd/211883 to your computer and use it in GitHub Desktop.
<html>
<head>
<title>Search</title>
</head>
<body>
{% if errors %}
<ul>
{% for error in errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
<form method="get" action=".">
<p><input type="text" name="q" />
<input type="submit" value="Search" /></p>
</form>
{% if query %}
<p>Your search for: <strong>{{ query }}</strong></p>
{% if books %}
<p>Found {{ books|length }} book{{ books|pluralize }}.</p>
<ul>
{% for book in books %}
<li>{{ book.title }}</li>
{% endfor %}
</ul>
{% else %}
<p>No books matched your search criteria.</p>
{% endif %}
{% endif %}
</body>
</html>
from django.shortcuts import render_to_response
from django.http import HttpResponse
from mysite.books.models import Book
def search(request):
errors = []
if request.GET.get('q', False):
query = request.GET['q']
if len(query) > 20:
errors.append('Please enter at most 20 characters.')
books = Book.objects.filter(title__icontains = query)
else:
errors.append('Enter a search term.')
return render_to_response('books/search.html', locals())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment