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="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<!-- jQuery UI !-->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></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">
</div>
In the same html file setup the jQuery autocomplete function in a script block
<script>
$(function() {
$("#places").autocomplete({
source: "/api/get_places/",
select: function (event, ui) { //item selected
AutoCompleteSelectHandler(event, ui)
},
minLength: 2,
});
});
function AutoCompleteSelectHandler(event, ui)
{
var selectedObj = ui.item;
}
</script>
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 url.py
file:
url(r'^api/get_places/', views.get_places, name='get_places'),
Then write up the view in views.py
:
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.city + "," + pl.state
results.append(place_json)
data = json.dumps(results)
else:
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.