我正在尝试通过遵循本教程来实现自动完成搜索
https://medium.com/@ninajlu/django-ajax-jquery-search-autocomplete-d4b4bf6494dd
我无法实现它,并且我认为它与我的网址或将脚本放入.html文件的方式有关。
我的搜索栏在索引视图中
index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.8.18/themes/base/jquery-ui.css" type="text/css" media="all" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script>
</head>
<body>
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'KPI/style.css' %}">
<script>
$(document).ready(function(){
$("#txtSearch").autocomplete({
source: "/login/index",
minLength: 2,
open: function(){
setTimeout(function () {
$('.ui-autocomplete').css('z-index', 99);
}, 0);
}
});
});
</script>
<form id="search" method="POST" action="{% url 'kpi:search' %}">
{% csrf_token %}
<input type="text" class="form-control" id="txtSearch" name="txtSearch">
<button type="submit" class="btn btn-default btn-submit">Submit</button>
</form>
</body>
</html>
urls.py
app_name = 'kpi'
urlpatterns = [
path('login/', views.LoginView.as_view(), name='login'),
path('login/index/', views.IndexView.as_view()),
]
现在在本教程中,它说要放置此路径url(r'^ajax_calls/search/', autocompleteModel),
,但看起来路径不一定要这样,所以我将路径更改为login/index/
并称为类视图{ {1}}像这样保存autocompleteModel
views.py
IndexView
Epic是我正在搜索的模型,其值为class IndexView(LoginRequiredMixin,TemplateView):
template_name = 'KPI/index.html'
def autocompleteModel(self,request):
if request.is_ajax():
q = request.GET.get('term', '').capitalize()
search_qs = Epic.objects.filter(name__icontains=q)
results = []
print(q)
for r in search_qs:
results.append(r.name)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return JsonResponse(data, mimetype)
。
使用上面的代码没有任何作用,我希望有人可以看到其中的缺陷。