November 30, 2007.
This article is not particularly polished, and expects some general Django knowledge. It does not require any JQuery experience.
Using Django with JQuery for Ajax is pretty easy, but figuring out how to do do a autocomplete form can be a bit more complex. So, here is a walkthrough.
/media /js jquery-1.2.1.js dimensions.js autocomplete.js autocomplete.css
and the smaller template:
Now we'll want to make our simple urls.py that we'll be communicating with (you'll need to update the name of the project and the application in the urls.py file):
from django.conf.urls.defaults import * urlpatterns = patterns('project.app.views', (r'^/lookup/$', 'book_lookup'), )
This may require a bit of tweaking to adapt to your specific situation, but it doesn't require any magic you haven't been exposed to in the Django tutorial.
A very very simple Book model that we'll be using to search by.
class Book(models.Model): name = models.CharField(max_length=200)
Our view is quite simple, simple parsing the incoming GET request, and sending back some serialized data.
from django.utils import simplejson from django.http import HttpResponse from project.app.models import Book def user_lookup(request): # Default return list results =  if request.method == "GET": if request.GET.has_key(u'query'): value = request.GET[u'query'] # Ignore queries shorter than length 3 if len(value) > 2: model_results = Book.objects.filter(name__icontains=value) results = [ x.name for x in model_results ] json = simplejson.dumps(results) return HttpResponse(json, mimetype='application/json')
Notice we use 'name__icontains' to search by the name of the books. This will probably translate into SQL as a LIKE query, which is historically considered to be a worse idea than delivering a nuclear warhead by a mule. It will likely be quite slow on a large database. This is an example, not production quality code.
And thats it for using JQuery to do some simple autocompletion. Django really does make these things quite simple, although it can be a bit confusing when you're getting started.
Let me know if you need any help.