Python Django Select2 Autocomplete Search using Ajax Example

Hi Dev,
In this tutorial, I will show you django select2 autocomplete using Ajax example. if you want to see example of python django select2 autocomplete using ajax then you are a right place. you will learn django select2 autocomplete example. it's simple example of django select2 autocomplete example in python. Let's get started with django select2 autocomplete example jquery ajax.
Here i will give you we will help you to give example of python django select2 autocomplete 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
django-admin startapp select2
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', 'select2', ]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 select2/models.py file and add the following code:
select2/models.pyfrom django.db import models # Create your models here. class Language(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField( auto_now_add = True)
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 select2/migrations/0001_initial.py
select2/migrations/0001_initial.py# Generated by Django 4.0.5 on 2022-06-21 12:31 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Language', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('created_at', models.DateTimeField(auto_now_add=True)), ], ), ]
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 select2/views.py file and add:
select2/views.pyfrom django.shortcuts import render from django.http import HttpResponse, JsonResponse from .models import Language # Create your views here. # Select2 Ajax Autocomplete def autocomplete(request): if 'term' in request.GET: term = request.GET.get('term') languages = Language.objects.all().filter(name__icontains=term) return JsonResponse(list(languages.values()), safe=False) return render(request, 'index.html')Step 7 : Creating Django Templates
Next, open the select2/templates/index.html file and the add:
/select2/templates/index.html<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Django Select2 Autocomplete Example</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" /> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script> <style type="text/css"> .select2-selection--single{ height: 37px !important; } </style> </head> <body> <div class="container mt-5 pt-5"> <div class="row d-flex justify-content-center"> <div class="col-md-7"> <div class="card"> <div class="card-header"> <h4>Python Django Select2 Autocomplete Search using Ajax Example</h4> </div> <div class="card-body"> <form> <div class="col-md-12"> <div class="form-group"> <label for="sel1">Select Language:</label> <select class="form-control js-data-example-ajax"></select> </div> </div> </form> </div> </div> </div> </div> </div> </body> <script type="text/javascript"> $(document).ready(function () { $('.js-data-example-ajax').select2({ ajax: { url: '{% url 'autocomplete' %}', dataType: 'json', processResults: function (data) { return { results: $.map(data, function (item) { return {id: item.id, text: item.name}; }) }; } }, minimumInputLength: 1 }); }); </script> </html>Step 8 : Creating Urls
In this section, we’ll create the urls to access our views.Go to the urls.py select2/urls.py file and update it as follows:
select2/urls.pyfrom django.urls import path from select2 import views urlpatterns = [ path('', 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('select2.urls')), ]Step 9 : 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/ address with a web browser.
I Hope It will help you....