Django, jQuery, and autocomplete


Question

After some extensive research (Googling), I cannot find a current tutorial on how to set up autocomplete using Django and jQuery. There appears to be a variety of plugins and there appears to be no consistency or standard about which to use or when.

I'm not a pro at either Django or jQuery, but need an autocomplete solution that is well documented and fairly simple to utilize.

Suggestions?

1
20
11/1/2018 2:34:26 AM

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.

16
2/22/2011 6:36:55 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon