The code of Lali

Blog — lalicode

jQuery Autocomplete and Django

June 15, 2016

In this tutorial we will go over how to use the jQuery AJAX Autocomplete Widget with Django. This tutorial is for those who already have a model and database setup.

First import jQuery and jQuery UI:

<!-- jQuery !-->
<script src=""> </script>
<!-- jQuery UI !-->
<link rel="stylesheet" href="">
<script src=""></script>
In your html template file add the following to your block content. You can replace places with whatever your model represents.
<div class="ui-widget">
  <label for="places">Places: </label>
  <input id="places">

In the same html file setup the jQuery autocomplete function in a script block


  $(function() {
      source: "/api/get_places/",
      select: function (event, ui) { //item selected
        AutoCompleteSelectHandler(event, ui)
      minLength: 2,

  function AutoCompleteSelectHandler(event, ui)
    var selectedObj = ui.item;


The jQuery autocomplete widget does all the heavy lifting for us. The AutoCompleteSelectHandler is called when the user selects an item from the list. The text selection is accessed with ui.item. However, it needs to invoke /api/get_places/. Let's get that set up!

Add the url in your file:

url(r'^api/get_places/', views.get_places, name='get_places'),

Then write up the view in

import json

def get_places(request):
  if request.is_ajax():
    q = request.GET.get('term', '')
    places = Place.objects.filter(city__icontains=q)
    results = []
    for pl in places:
      place_json = {}
      place_json = + "," + pl.state
    data = json.dumps(results)
    data = 'fail'
  mimetype = 'application/json'
  return HttpResponse(data, mimetype)

Here we setup what goes into the autocomplete search terms based on the user's search term, q. The function filters through your database and returns a json file with the correct data to the jQuery autocomplete function.

You should be all good to go now! Special thanks to Flaviu with his tutorial on how to do this.


April 29, 2016

to the lali