Django and JQuery: Integrating Django and JQuery Autocomplete plugin

I have many what would otherwise be very large select input fields. I need some autocomplete support. I decided on JQuery (http://jquery.com) and its autocomplete plugin (http://docs.jquery.com/Plugins/Autocomplete).

This assumes that you have at least gone through the Django tutorial.

To support this I added the following to settings.py of the django instance.

JQUERY_ROOT = ‘/home/csmadmin/tools/jquery’

The above has where I downloaded and installed JQuery and the JQuery autocomplete plugin.

Then to serve up these files I add the following to urls.py

(r’^js/(?P.*)$’, ‘django.views.static.serve’,
{‘document_root’: settings.JQUERY_ROOT}),

Then I adapted the example they gave in the JQuery autocomplete plugin to work with django.

I created two views to server up plain text and json respectively (for months and emails).

months_data = “””
January
Feburary
March
April
May
June
July
August
September
October
November
December
“””

emails_data = [
{ “name”: “Peter Pan”, “to”: “peter@pan.de” },
{ “name”: “Molly”, “to”: “molly@yahoo.com” },
{ “name”: “Forneria Marconi”, “to”: “live@japan.jp” },
{ “name”: “Master Sync“, “to”: “205bw@samsung.com” },
{ “name”: “Dr. Tech de Log”, “to”: “g15@logitech.com” },
{ “name”: “Don Corleone”, “to”: “don@vegas.com” },
{ “name”: “Mc Chick”, “to”: “info@donalds.org” },
{ “name”: “Donnie Darko”, “to”: “dd@timeshift.info” },
{ “name”: “Quake The Net”, “to”: “webmaster@quakenet.org” },
{ “name”: “Dr. Write”, “to”: “write@writable.com” }
];

def months(request):
query = request.GET.get(“q”, “”)

if len(query) == 0 or query[0] == ” ” :
data = months_data
else:
month_list = months_data.split(‘\n’)
print “ml ” + `month_list`
print “qy ” + `query`
data = “\n”.join([month for month in month_list
if month.lower().find(query) != -1])
print “dt ” + `data`
return HttpResponse(data, mimetype = ‘text/plain’)

def emails(request):
query = request.GET.get(“q”, “”)

if len(query) == 0 or query[0] == ” ” :
json = simplejson.dumps(emails_data)
else:
json = simplejson.dumps([email for email in emails_data
if email[‘name’].find(query) != -1
or email[‘to’].find(query) != -1 ])
return HttpResponse(json, mimetype = ‘application/json’)

Don’t you just love list comprehensions. 🙂 The above filters the lists based on the query string that was sent(with a HTTP get).

Then we just change the index.html to handle the JSON request. I changed the base.html template to support JavaScript as follows:

{% autoescape on %}



{% block title %}My amazing site{% endblock %}

{% block css %} {% endblock %}

{% block javascript %}

{% endblock %}

Submental Mutterings

{% block content %}

27 October 2001

I sit here in a lone island of light, tapping away, trying to stay awake. I’m the only one who isn’t trying to grab some sleep as we speed east. Three hours knocked out of the night without even trying, thanks to the time zones we have to cross; everyone’s hoping to spend as much of the four hours we’ll be aloft as possible asleep. Except me. I’m doing my damndest to keep myself alert so that when I get home, I’ll have been awake all night, just like my wife back in Cleveland. So we can go to sleep together, be together for the first time in a week.

It helps that my body thinks it’s only 2:14am, despite the fact that it’s 5:14am where we’re headed, where it’s home. I’ve been staying up late all week anyway. Lying alone in my hotel room bed is like standing in a deserted concert hall, hollow and unused despite my presence. There isn’t enough of me to fill the space available. The surface of the mattress is too flat because I’m the only one deforming it. I kept lying there in my lone valley, trying to distract my hindbrain with late-night Comedy Central, where strangely enough they’re showing Saturday Night Live reruns every night of the week.

But now the week is over, and I’m slipping eastward at 600 miles an hour and six miles aloft, arrowing through the sky in a small pool of light. Power bleeds slowly out of my laptop battery, music pours through the headphones into my ears, and the thin air rushes past the skin of the plane. I keep glancing out the window as though something will be there.

Soon I will see my wife again, will be home. Through the exhaustion I can feel happiness, deep and solid.

{% endblock %}



{% endautoescape %}

Notice that I have a javascript block and a css block.

Then we install the django autocomplete feature as follows:

{% extends “patientmgmt/base.html” %}

{% block title %}PM Index{% endblock %}

{% block javascript %}





{% endblock %}

{% block content %}

Here is some content

{% endblock %}

The above works. There might be better ways to combine Django and JQuery. In fact, you can almost count on it. I was able to get the above working fairly quickly and it is certainly one way to combine a JavaScript library with Django site.

Please feel free to comment on this and let me know where I can improve.

–Rick Hightower