我正在尝试在django中构建jquery自动完成,但它在浏览器中返回此响应"视图rango.views.AutoCompleteView没有返回HttpResponse对象。"我哪里错了?
搜索框
<form id = "aa" class = "form-inline" method = "post" action="">
{% csrf_token %}
<input type="text" name = "cat_name" class = "form-control" id = "cat" value = ""/>
<input class ="btn btn-sm btn-info" type="submit"/>
</form>
的javascript
$(function() {
$("#cat").autocomplete({
source: "/rango/autocomplete/",
minLength:2,
});
});
视图
class AutoCompleteView(FormView):
def get(self,request,*args,**kwargs):
data = request.GET
item = data.get("term")
if item:
cats = Category.objects.filter(name__icontains = item)
else:
cats = Category.objects.all()
results = []
for cat in cats:
cat_json = {}
cat_json['id'] = cat.id
cat_json['label'] = cat.item
cat_json['value'] = cat.item
results.append(cat_json)
data = json.dumps(results)
mimetype = 'application/json'
return HttpResponse(data,mimetype)
urls.py
url(r'^autocomplete/$',AutoCompleteView.as_view())
答案 0 :(得分:0)
请注意,只有在您没有“期限”的情况下,您的观看才会返回HttpResponse
在request.GET
中或在Category
模型中有条目。尝试使用此缩进重写代码:
class AutoCompleteView(FormView):
def get(self,request,*args,**kwargs):
data = request.GET
item = data.get("term")
if item is not None:
cats = Category.objects.filter(name__icontains = item)
else:
cats = Category.objects.all()
results = []
for cat in cats:
cat_json = {}
cat_json['id'] = cat.id
cat_json['label'] = cat.item
cat_json['value'] = cat.item
results.append(cat_json)
data = json.dumps(results)
mimetype = 'application/json'
return HttpResponse(data, mimetype)
了解它的不同之处,这样您无论如何都会返回HttpResponse
。
答案 1 :(得分:0)
您需要返回一个列表,因此您需要使用 json.dumps()功能,并且您的缩进看起来非常糟糕,不要对齐返回在 for循环 。
中return HttpResponse(json.dumps(results))
请关注@ valentjedi的回答。