Autocomplete Search

models.py

from django.db import models

# Create your models here.
class City(models.Model):
    name = models.CharField(max_length=100)
    population = models.IntegerField()

admin.py

from django.contrib import admin
from .models import City
# Register your models here.

admin.site.register(City)

views.py

from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from .models import City
# Create your views here.
def home(request):
  return render(request,'autocomplete/index.html')

def autocomplete(request):
    term = request.GET.get('term', '')
    suggestions = City.objects.filter(name__icontains=term).values_list('name', flat=True)
    return JsonResponse(list(suggestions), safe=False)

Templates

templates/autocomplete/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.1/themes/smoothness/jquery-ui.css">
</head>
<body>
    <input type="text" id="my-input" name="my-input" />
    <script>
        $(function() {
            $('#my-input').autocomplete({
                source: '{% url "autocomplete" %}',
                minLength: 2,
            });
        });
        </script>
</body>
</html>

urls.py

from django.urls import path
from . import views
urlpatterns = [
    path('',views.home,name='home'),
    path('autocomplete/', views.autocomplete, name='autocomplete'),
]

Last updated