Johnny Dahdah
Johnny Dahdah

Reputation: 1015

Javascript Autocomplete Function with Django

I've been trying to use the javascript autocomplete function with a Django/Python array, and I never get it working properly. Here is my template script:

    <script>
       $(function() {
         var availableTags = "{{bandas.ba_nombre}}"
         $( "#tags" ).autocomplete({
           source: availableTags
       });
    });
    </script>

And then I have my HTML input box <input id="tags" />.

I've read on some web sites that another way is to dump Python array into JSON, and I get the following error: Invalid filter: 'jsonify'

Here is my Python code for JSON implementation:

    register = Library()

    def jsonify(object):
      if isinstance(object, QuerySet):
        return mark_safe(serialize('json', object))
      return mark_safe(simplejson.dumps(object))

    register.filter('jsonify', jsonify)
    jsonify.is_safe = True 

And my script:

    <script>
       $(function() {
         var availableTags = jQuery.parseJSON('{{bandas.ba_nombre|jsonify }}');
    alert(availableTags.length);
       $( "#tags" ).autocomplete({
         source: availableTags
       });
    });
    </script>

Is there another way? Or what am I doing wrong?

Upvotes: 0

Views: 357

Answers (2)

yuvi
yuvi

Reputation: 18427

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.

Upvotes: 0

MaZZly
MaZZly

Reputation: 124

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/

Upvotes: 1

Related Questions