Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, jQuery, and autocomplete

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?

like image 598
harwalan Avatar asked Feb 22 '11 05:02

harwalan


2 Answers

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.

like image 162
CraigKerstiens Avatar answered Nov 19 '22 15:11

CraigKerstiens


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/

like image 7
Mihai Zamfir Avatar answered Nov 19 '22 14:11

Mihai Zamfir