How to Autocomplete Search using Typeahead Js in Django ?

Hi Dev,
Today our leading topic is django typeahead js autocomplete search using Ajax example. I would like to show you python django typeahead js autocomplete search using ajax. let’s discuss about django typeahead js autocomplete example. step by step explain django typeahead js autocomplete example in python. Follow bellow tutorial step of django typeahead js search autocomplete example jquery ajax.
Here i will give you we will help you to give example of python django typeahead js autocomplete search using jquery ajax example. So let's see the bellow example:
Step 1 : Create a ProjectIn this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:
django-admin startproject autocompleteStep 2 : Create a App
python3 manage.py startapp typeahead
Next, you need to add it in the settings.py file as follows:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'typeahead', ]Step 3 : Database Setup
Next step, we will modify the settings.py file and update the database settings to configure the mydb database:
settings.pyDATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'autocomplete', 'USER':'root', 'PASSWORD':'root', 'HOST':'localhost', 'PORT':'3306' } }Step 4 : Create a Model
In this step we will require the database model for storing contacts.Open the typeahead/models.py file and add the following code:
typeahead/models.pyfrom django.db import models # Create your models here. class Language(models.Model): title = models.CharField(max_length=255)
After creating these model, you need to create migrations using the following command:
Step 5 : Create a Migrationspython manage.py makemigrations
After successfully run the above command go to the typeahead/migrations/0001_initial.py
typeahead/migrations/0001_initial.py# Generated by Django 4.0.6 on 2022-07-04 11:37 import ckeditor_uploader.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Language', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255)) ], ), ]
Next, you need to migrate your database using the following command:
python manage.py migrateStep 6 : Creating the Views
In this step, we need to create the views for performing fetch record to the database.Open the typeahead/views.py file and add:
typeahead/views.pyfrom django.shortcuts import render from django.http import HttpResponse, JsonResponse from .models import Language import json # Create your views here. def search(request): return render(request, 'autocomplete.html') # Typeahead Js Ajax Autocomplete def autocomplete(request): results = [] if request.method == "GET": if request.GET.get('query'): value = request.GET['query'] model_results = Language.objects.all().filter(title__icontains=value) for x in model_results: results.append(x.title) data = json.dumps(list(results)) return HttpResponse(data, content_type='application/json')Step 7 : Creating Django Templates
Next, open the typeahead/templates/index.html file and the add:
/typeahead/templates/index.html<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>How to Autocomplete Search using Typeahead Js in Django</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script> </head> <body> <div class="container mt-5 pt-5"> <div class="row d-flex justify-content-center"> <div class="col-md-9"> <div class="card"> <div class="card-header"> <h5>How to Autocomplete Search using Typeahead Js in Django ? - <span class="text-primary">Tuts-Station.com</span></h5> </div> <div class="card-body"> <form> <div class="col-md-12"> <div class="form-group"> <label for="sel1">Select Language:</label> <input class="typeahead form-control" id="search" type="text"> </div> </div> </form> </div> </div> </div> </div> </div> </body> <script type="text/javascript"> /*------------------------------------------ -------------------------------------------- About -------------------------------------------- --------------------------------------------*/ $(document).ready(function () { var path = "{% url 'autocomplete' %}"; $('#search').typeahead({ source: function (query, process) { return $.get(path, { query: query }, function (data) { return process(data); }); } }); }); </script> </html>Step 8 : Creating Urls
In this section, we’ll create the urls to access our views.Go to the urls.py typeahead/urls.py file and update it as follows:
typeahead/urls.pyfrom django.urls import path from typeahead import views urlpatterns = [ path('search/', views.search), path('autocomplete-search', views.autocomplete, name='autocomplete'), ]
Next, we will require the modify the urls.py your root preoject folder lets update the file.
autocomplete/urls.pyfrom django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('typeahead.urls')), ]Run the Server
In this step, we’ll run the local development server for playing with our app without deploying it to the web.
python manage.py runserver
Next, go to the http://localhost:8000/search address with a web browser.
I Hope It will help you....