Skip to content
Related Articles

Related Articles

Implement Search Autocomplete For Input Fields in Django

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 16 Feb, 2021
View Discussion
Improve Article
Save Article

Django is a high-level Python  based Web Framework that allows rapid development and clean, pragmatic design.  It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database – SQLlite3, etc. Today we will create joke app in django.

In this article we will learn how to fetch data from django models and give it feature like autocomplete. We will be using jquery for autocompletion.

Installation :

Ubuntu

pip3 install django

First we will create new project

django-admin startproject AutoC
cd AutoC

Then we will create new app

python3 manage.py startapp main

Then add the app name in settings.py inside the INSTALLED_APPS

 models.py

Python3




from django.db import models
  
# Create your models here.
class Language(models.Model):
    name = models.CharField(max_length=20)
  
    def __str__(self):
        return f"{self.name}"


Then to create database table we have to makemigrations

python3 manage.py makemigrations
python3 manage.py migrate

I have added this languages in the table.


Python3




from django.shortcuts import render
from .models import Language
  
# Create your views here.
def home(request):
    languages = Language.objects.all()
    return render(request,'main/index.html',{"languages":languages})


Then create new directory inside app  template inside that create another directory main

Then create new file index.html

HTML




<!DOCTYPE html>
<html>
<head>
    <title>AutoComplete</title>
    <script src=  
    </script>  
    
    <script src=  
    </script>  
    
    <link href=  
        rel="stylesheet" type="text/css" />  
</head>
<body>
    <h1>Welcome to GFG</h1>
    <input type="text" id="tags">
    <script>
  $( function() {
    var availableTags = [
        {% for language in languages %}
            "{{language.name}}",
        {% endfor %}
    ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  } );
  </script>
</body>
</html>


Then create new file urls.py

Python3




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


Then add the app/urls inside our project/urls

AutoC/urls.py

Python3




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


Then to run this app 

Windows

python manage.py runserver

Ubuntu

python3 manage.py runserver


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!