Jquery Autocomplete plugin with Django (Trey Piepmeier solution)

Posted by Sally on Stack Overflow See other posts from Stack Overflow or by Sally
Published on 2010-04-13T02:59:21Z Indexed on 2010/04/13 3:02 UTC
Read the original article Hit count: 368

So, I'm basing my code on Trey's solution on:
http://solutions.treypiepmeier.com/2009/12/10/using-jquery-autocomplete-with-django/

The script is:

    <script>
        $(function() {
        $('#id_members').autocomplete('{{ object.get_absolute_url }}members/lookup', {
            dataType: 'json',
            width: 200,
            parse: function(data) {
                return $.map(data, function(row) {
                    return { data:row, value:row[1], result:row[0] };
                });
            }
            }).result(
                function(e, data, value) {
                    $("#id_members_pk").val(value);
                }
            );
        }
    );
   </script>

The views.py:

def members_lookup(request, pid):  
    results = []
    if request.method == "GET":
        if request.GET.has_key(u'q'):
            value = request.GET[u'q']
            # Ignore queries shorter than length 1
            if len(value) > 2:

                model_results = Member.objects.filter(
                                Q(user__first_name__icontains=value) | Q(user__last_name__icontains=value)
                                )
                results = [ (x.user.get_full_name(), x.id) for x in model_results ]
    json = simplejson.dumps(results)
    print json
    return HttpResponse(json, mimetype='application/json')

The problem is:
It stops refining the search results after the initial lookup. For example:
If I set len(value) > 2, after I type the 3rd character it will give me a list of suggestions. But if I keep on typing the 4th or 5th character, the list of suggestions doesn't change.

Any suggestions on why this is?

© Stack Overflow or respective owner

Related posts about django

Related posts about jquery-plugins