Jquery Autocomplete plugin with Django (Trey Piepmeier solution)
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,开发者_JS百科 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?
For server side I recommend you take a look an ajax selects application
I solved it by passing a string from the view side in the format that jquery autocomplete can parse easier.
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)
)
for r in model_results:
results += '%s|%s\n' % (r.user.get_full_name(), r.id)
return HttpResponse(results, mimetype='text/html')
Then on the client side:
<script>
$().ready(function() {
$("#id_members").autocomplete("{{ object.get_absolute_url }}members/lookup/", {
width: 260,
minChars: 2,
selectFirst: false
});
$("#id_members").result(function(event, data, formatted) {
if (data)
$(this).parent().next().find("input").val(data[1]);
});
});
</script>
精彩评论