AJAX Autocomplete Search With Django and jQuery
Let’s say you have some data that you want to autocomplete in a text field as the user types.
This is what your Django model might look like if you were searching for drug names:
1 2 3 4 5 |
|
It’s very likely that your data is in a different format (csv or pipe delimited), like this:
1 2 |
|
So we need to import that data. A database copy command (postgres, mysql, sqlite) will not deal very nicely with our Django auto-incrementing keys, so we need to add the data using a django view, such as this:
1 2 3 4 5 6 7 8 |
|
Now load the django console and import the data:
1 2 3 |
|
Cool. Now we need to actually write the template where the search is. We’ll use jQuery Autocomplete because that’s what the cool kids do. Let’s first import jQuery and jQueryUI in our base template:
1 2 3 |
|
Now let’s add this to the template we want the search field on:
1 2 3 4 |
|
Our own javascript to get the autocomplete is this (you can put it anywhere after the jQuery imports):
1 2 3 4 5 6 |
|
Where is the ajax call happening? jQuery Autocomplete does it for us. But how does it know which fields to get? It doesn’t! Let’s implement the url:
1
|
|
And now,the real work. Our view:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
Note that jQuery autocomplete sends the query as “term” and it expects back three fields: id, label, and value. It will use those to display the label and then the value to autocomplete each drug.
We now have an AJAX jQuery Autocomplete Search with Django. Hope this helps.