Last active
September 15, 2015 21:44
-
-
Save boniattirodrigo/96c074bb09187b5a0447 to your computer and use it in GitHub Desktop.
Autocomplete with Django and AJAX
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$("#input").autocomplete({ | |
minLength: 1, | |
source: function(req, add){ | |
var search=$("#input").val(); | |
$.ajax({ | |
url: '/your-url/', | |
async: true, | |
dataType: 'json', | |
type: 'GET', | |
data: {'start': search,}, | |
success: function(data){ | |
var suggestions=[]; | |
$.each(data, function(index, object){ | |
suggestions.push(object.username); | |
}); | |
add(suggestions); | |
}, | |
error: function(){ | |
alert("Error!"); | |
} | |
}); | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
def your-view(request): | |
if request.is_ajax: | |
input_username = request.GET.get('start', '') | |
users = User.objects.filter( | |
Q(username__icontains=input_username) | | |
Q(id__icontains=input_username) | |
).order_by('username')[:5] | |
results=[] | |
for User in users: | |
User_json={} | |
User_json['username']=User.username | |
results.append(User_json) | |
data_json=json.dumps(results) | |
else: | |
data_json='fail' | |
mimetype="application/json" | |
return HttpResponse(data_json, mimetype) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment