[Answer]-Javascript Autocomplete Function with Django

1👍

I’d say go with Django-autocomplete-light

It is a bit tricky to learn at first, but afterwards helps alot with generation of autocomplete fields
https://github.com/yourlabs/django-autocomplete-light/

👤MaZZly

0👍

I have some experience with using jQuery UI autocomplete alongside django, and have found out that there is a general problem with the two combining. In essence, this is because you can’t send a response that is partially-JSON, so you either return available_tags already in the right format for jQuery UI or use another function that just returns the tags. To give you an example of the two approaches.

  1. Send the data already formatted in the server-side. This is a kind of brute-force sort of way and isn’t very recommended but might serve your needs well enough:

    server-side:

    available_tags = ['example', 1, 2, 'test']
    return render_to_response('mytemplate.html', {'available_tags': repr(available_tags) })
    

    client-side:

        $( "#tags" ).autocomplete({
              source: {{ availableTags }} //notice I didn't put '' around it...
           });
    
  2. Use another response and fetch it dynamically:

    server-side:

    def main(request):
        ...
        return render_to_response('mytemplate.html')
    
    def get_tags(request):
        data = {'example': 1, 'code': 2}
        return HttpResponse(json.dumps(data), content_type="application/json")
    

    client-side:

    var available_tags = $.get('get_tags/', function(data) { ...parse the json and whatnot... });
    

Granted, the second option is more recommended, but at times I also used the first one. You might need to change it up and use it a bit differently (the repr can be problematic, especially if using unicode and such) but it’s a trial-and-error thing and you get the idea.

👤yuvi

Leave a comment