Django, jQuery, and autocomplete
If you're looking to search from within your django models then something like:
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:
function searchOpen() { var search = $('#txtSearch').val() var data = { search: search }; $.ajax({ url: '/search.json', data: data, dataType: 'jsonp', jsonp: 'callback', jsonpCallback: 'searchResult' });}function searchResult(data) { $( "#txtSearch" ).autocomplete ({ source: data });}
Finally to connect it all on your input form would have something like:
<input type="text" name="search" id="txtSearch" onkeyup="searchOpen()" />
Note, this is using Jquery UI as well in addition to stock jQuery.
Meanwhile, a good tutorial appeared.
autocomplete
does everything for you, all you have to do is the following:
js
$(function() { $("#search-field").autocomplete({ source: "/ajax_calls/myFunction", minLength: 2, });});
urls.py
url(r'^ajax_calls/myFunction/', 'my_app.views.handler_function'),
views.py
def get_drugs(request): if request.is_ajax(): ..... data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype)
SOURCE:http://flaviusim.com/blog/AJAX-Autocomplete-Search-with-Django-and-jQuery/
Let's say you want to set up autocomplete on some input field (like <input type="text" id="id_input">
) with the username of your users. This is the way I did it:
urls.py
First of all, add a url that will be used by the AJAX call.
url(r'^ajax/autocomplete/$', views.autocomplete, name='ajax_autocomplete')
views.py
Then set a view to retrieve the information (i.e the usernames, in this case) from the database
from django.http import JsonResponsedef autocomplete(request): if request.is_ajax(): username_query = request.GET.get('username_query', '') usernames = (User.objects .filter(username__startswith=username_query) .values_list('username', flat=True)) data = { 'usernames': usernames, } return JsonResponse(data)
JavaScript
Finally, you need to make a JavaScript function that goes to the database and returns the usernames that match with the value of the input field every time you press (and release) a key. For this, we are going to use Ajax, JQuery and the JQuery-ui's autocomplete function
jQuery(function() { $("#id_input").on('keyup', function(){ let value = $(this).val(); $.ajax({ url: "{% url 'ajax_autocomplete' %}", data: { 'username_query': value }, dataType: 'json', success: function (data) { let usernames = data.usernames; $("#id_input").autocomplete({ source: usernames, minLength: 3 }); } }); }); });
And that's it! For more information, you can check out this tutorial