I’m using this JQuery autocomplete plugin http://www.devbridge.com/projects/autocomplete/jquery/ in my project. I followed this tutorial http://tips4php.net/2010/09/ajax-autocomplete-with-jquery-and-php/.
jQuery code for Autocomplete:
$('#add-keywords').autocomplete({
serviceUrl:'/keywords_suggestions',
minChars:3,
maxHeight:220,
width:280,
zIndex: 9999,
onSelect: function(value, data){ $('#add-keywords').val(value); },
});
The Ajax GET request from JQuery Autocomplete has no problem. It is like, if I type “developer” in the input text the GET request url would be
http://127.0.0.1:8000/keywords_suggestions/?query=developer
I’m getting that parameter query in Django like this:
def kkeywords_suggestions(request):
if request.is_ajax():
q = request.GET.get('query', '')
try:
g = KeywordsModel.objects.filter(keyword__startswith=q).order_by('count')
except KeywordsModel.DoesNotExist:
return HttpResponse("not")
else:
for i in range(1,(len(g)+1)):
s = []
s.append(g[i-1].keyword)
to_json = {
query: q,
suggestions: s,
}
return HttpResponse(simplejson.dumps(to_json), mimetype='application/json')
Django Models.py:
class KeywordsModel(models.Model):
keyword = models.CharField(max_length=40, blank=False)
count = models.IntegerField(max_length=20)
The problem occurs from here request.GET.get('query', ''). It shows the error
ValueError at /keywords_suggestions/
The view information.views.keywords_suggestions didn't return an HttpResponse object.
UPDATE-1
Sorry, the error in Chrome Network tab is like this
Request URL:http://127.0.0.1:8000/keywords_suggestions/?query=web
Request Method:GET
Status Code:500 INTERNAL SERVER ERROR
When I checked in that URL, It shows blank page. Why?
UPDATE-2
I removed request.is_ajax() from the views. Now I’m getting this error:
Exception Type: NameError
Exception Value:
global name 'query' is not defined
Exception Location: /home/nirmal/try/information/views.py in keywords_suggestions, line 123
Why django considering query as a global name? It is the one I’m trying to fetch from the url.
Could anyone help me to make a perfect HttpResponse for that Autocomplete feature?
Thanks!
it should be.
basically what was happening is that
{query:q ...python was looking for the variable query in order to set the key in the dictionary, to what ever string query may have being pointing to, but no such variable existed and such it returned an error …global name 'query' is not definedas the error states, python was looking for variable query, it first checks locally in the function scope and then it moves upwards until it hits the global scope if it isn’t found it throws that exception.