Skip to main content

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:

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: