I know that implementing jQuery autocomplete is tricky. Here is a working example for Django > 2.0:
Step 1: Create a simple HTML with an input (Don't forget to add links to load jQuery and jquery-ui). Save the code as testsearch.html
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
</head>
<div class="ui-widget">
<label for="search"> Search </label>
<input id="search">
</div>
Step 2: Add a JavaScript code to the html. It calls the function autocomplete from jquery-ui. This function uses a source which the URL for Ajax calls
<script type="text/javascript">
$(function() {
$("#search").autocomplete({
source: "{% url 'project:ajax_load_project' %}",
minLength: 2,
});
});
</script>
Step 3: Now we need to create two functions. A simple function to render testsearch.html and another one that receives Ajax calls and send back data.
def ajax_load_project(request):
if request.is_ajax():
q = request.GET.get('term', '')
print(q)
projects = Project.objects.filter(title__istartswith=q)[:5]
results = []
for project in projects:
project_json = {}
project_json['id'] = project.id
project_json['value'] = project.title
project_json['label'] = project.title
results.append(project_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
def searchProject(request):
template = 'project/testsearch.html'
return render(request, template)
Project is my model. You can replace it with your Model. Replace title with the field used for searching.
For my example you can create this simple Model:
class Project(models.Model):
"""
A Model representing a the project.
"""
title = models.CharField(max_length=200)
Step 4: Don't forget to include two URLs. One for the HTML and the one for Ajax calls
urlpatterns += [
#test search
path('SuggestProject/', views.ajax_load_project, name='ajax_load_project'),
path('searchtest/', views.searchProject, name='searchProject'),]