I have a search form and it works fine. Now I would like my search form autocomplete.I tried using django autocomplete light but I have a problem implementing it.
I
Django-autocomplete-light is tricky to set up and in my opinion its easier using other autocompletes.
Here is how I got it working using bootstrap 2. (There is a bootstrap 3 compatible library as well, and the configuration is more or less the same https://github.com/bassjobsen/Bootstrap-3-Typeahead).
You need a few things to work together.
1: Create a view that will process the autocomplete request and return suggestions. so in views.py
def book_autocomplete(request, **kwargs):
term = request.GET.__getitem__('query')
books = [str(book) for book in book.objects.filter(Q(title__icontains=q) | Q(description__icontains=q))]
return HttpResponse(json.dumps(books))
And in urls.py add an entry:
url(r'^autocomplete/book_autocomplete/' , booking.ebsadmin.book_autocomplete , name='book_autocomplete'),
2: Load the bootstrap typeahead/autocomplete code into your page. The project I inherited was already using bootstrap 2, so this code was already there. So in your template in the head section (this will probably differ depending on the the directory structure of your static files):
3: Connect the bootstrap typeahead/autcomplete to your view. I created a file book_autocomplete.js, and added it to my static files folder. This tells it to attach the autocomplete to the element with id book-search (you will have to give the search box on your form and id equivalent to the '#book-search' that I have used here. An example on how to do this in your form definition https://stackoverflow.com/a/5827671/686016):
book_search_typeahead.js
$(document).ready(function() {
$('#book-search').typeahead({source: function (query, process) {
return $.getJSON(
'/autocomplete/book_autocomplete/', // this is the url for the view we created in step 1
{ query : query },
function (data) {
console.log(data) ;
return process(data);
});
}});
});
back to your template and add this line to load the javascript that we just created:
I think that is everything.