JQuery and Django Autocomplete

In a couple of various places I’ve seen light requests of how to put autocomplete in for a Django web application. Here’s a really light weight version with a view and autocomplete functionality using:

For a view to search within your django model it would look something like:

models.py
1
2
3
4
5
6
7
8
from django.utils import simplejson
def autocompleteModel(request):
    search_qs = ModelName.objects.filter(name__startswith=request.REQUEST['search'])
    results = []
    for r in search_qs:
        results.append(r.name)
    resp = request.REQUEST['callback'] + '(' + simplejson.dumps(result) + ');'
    return HttpResponse(resp, content_type='application/json')

For the jQuery autocomplete and call:

Comments