Я пытаюсь реализовать поиск автозаполнения, следуя этому руководству
https://medium.com/@ninajlu/django-ajax-jquery-search-autocomplete-d4b4bf6494dd
И мне не удается его реализовать, и я думаю, что это как-то связано смои URL-адреса или способ размещения сценариев в моем файле .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/
и вызвал классview IndexView
, который содержит autocompleteModel примерно так:
views.py
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)
Epic - модель, в которой я ищу со значением name
.
скод, который у меня есть выше, ничего не делает, и я надеюсь, что кто-то увидит в нем изъян.