Django REST Framework is a robust and flexible toolkit for building Web APIs. It is written in python and allows the user to create some cool and awesome web applications. In this blog we will learn how to implement search autocomplete for input fields in Django. Search autocomplete is something that we use most of the time while filling forms, searching something and many more. This feature can make your application more interactive and user friendly as well. So let’s start.

Implement Search Autocomplete For Input Fields in Django

Implementations

Step 1. Create Django Project

We are first going to create a django project and an app inside that project .


1. Create a Django project.

django-admin startproject blog22

2. Create an app in that django-project.

python manage.py startapp autocomplete

3. Add your app name in installed apps.

Settings.py

INSTALLED_APPS = [
    'autocomplete',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Step 2. Add files and Folder to the Django Project

We need to create a template folder in the django folder and a urls.py file in the app folder.

  1. Create a new folder in the django folder(here,blog22) save it with the name template.
  2. Add the path for this template folder in blog22 > settings.py .

Settings.py

import os
 
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'template')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

3. Create a new file in the app folder(here, autocomplete) save it with the name urls.py .

4. Add path for this url.py file in blog22 > urls.py .

Urls.py

from django.contrib import admin
from django.urls import path,include
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('autocomplete.urls'))
]

Step3. Implement Search Autocomplete

We first have to create a model and some instances of it that we want to show for autocomplete. Let suppose you have a field to fill student name so the autocomplete should work like whenever you press the first alphabet key then the student names having that alphabet in their name will appear, so for creating autocomplete we need to have data to search within, That is why we first need to create a model and add its object in database.

  1. Create a model in app_name (here, autocomplete ) > models.py.

Models.py

from django.db import models
 
# Create your models here.
class CarBrand(models.Model):
    name=models.CharField(max_length=100)

2. Run migrations with the help of the following command.

python manage.py makemigrations
python manage.py migrate

3. Register your created model in app_name (here, autocomplete ) > admins.py.

Admins.py

from django.contrib import admin
from .models import CarBrand
# Register your models here.
 
class CarAdmin(admin.ModelAdmin):
    list_display = ['name']
admin.site.register(CarBrand,CarAdmin)

4. Now create a superuser by running the following command and add your credentials.

python manage.py createsuperuser

Add objects and your dashboard will look like this.

Implement Search Autocomplete For Input Fields in Django

5. Create Html File.

Index.html

<!DOCTYPE html>
<html>
 
<head>
    <title>AutoComplete</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js">
    </script>
 
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js">
    </script>
 
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/ui-lightness/jquery-ui.css" rel="stylesheet"
        type="text/css" />
</head>
 
<body>
 
    <input type="text" id="tags">
    <script>
        $(function () {
            var availableTags = [
                {% for car in brand %}
            "{{car.name}}",
            {% endfor %}
    ];
        $("#tags").autocomplete({
            source: availableTags
        });
  } );
    </script>
</body>
 
</html>

6. Provide a path for the above html files and actions in app_name ( here, autocomplete ) > urls.py.

Urls.py

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

7. Create function for the path provided in urls file in app_name ( here, autocomplete) > views.py.

Views.py

from django.shortcuts import render
from .models import CarBrand
# Create your views here.
def index(request):
    brand=CarBrand.objects.all()
    return render(request,'index.html',{'brand':brand})
Output :-
Implement Search Autocomplete For Input Fields in Django

Quick Revision

  1. Create your django project folder.
  2. Create an app folder in the django project folder.
  3. Add template folder in the django folder and provide its path in django_folder > settings.py .
  4. Add file named as urls.py in the app folder and provide its path in django_project > urls.py.
  5. Create a model and register it in app_folder > admins.py.
  6. Add html code for the  in django_project > template.
  7. Add path of index html page in app_folder > urls.py.
  8. Create function for the index html page in app_folder >views.py.

GitHub Link :-

https://github.com/jaya2320/blog_search_autocomplete

Conclusion

So, we learned how to implement search autocomplete for input fields in Django. I hope this blog will be useful for you and helps you to understand each and every step. Hope all your doubts get cleared. Thank you.