Q> Create a Django app that lets users type the first few letters of a movie,
and returns matching movie names using AJAX (without reloading the
page).
Step-by-Step Implementation
1. Create Django Project & App
django-admin startproject moviesearch
cd moviesearch
python manage.py startapp searchapp
2. Add searchapp to Installed Apps
In moviesearch/settings.py:
INSTALLED_APPS = [
...
'searchapp',
]
3. Create Movie Model
In searchapp/models.py:
from django.db import models
class Movie(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
Run migrations:
python manage.py makemigrations
python manage.py migrate
You can populate movies via Django admin or shell.
4. Create a View for AJAX Search
In searchapp/views.py:
from django.http import JsonResponse
from django.shortcuts import render
from .models import Movie
def home(request):
return render(request, 'searchapp/home.html')
def search_movies(request):
query = request.GET.get('query', '')
if len(query) >= 3:
movies =
Movie.objects.filter(name__istartswith=query).values_list('name', flat=True)
return JsonResponse(list(movies), safe=False)
return JsonResponse([], safe=False)
5. Configure URLs
In searchapp/urls.py (create this file):
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('ajax/search/', views.search_movies, name='search_movies'),
]
In moviesearch/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('searchapp.urls')),
]
6. Create HTML Template
In searchapp/templates/searchapp/home.html:
<!DOCTYPE html>
<html>
<head>
<title>Movie Search</title>
<script>
function fetchMovies() {
const query = document.getElementById('movieInput').value;
if (query.length < 3) {
document.getElementById('results').innerHTML = '';
return;
}
fetch(`/ajax/search/?query=${query}`)
.then(response => response.json())
.then(data => {
let html = '<ul>';
data.forEach(movie => {
html += `<li>${movie}</li>`;
});
html += '</ul>';
document.getElementById('results').innerHTML = html;
});
}
</script>
</head>
<body>
<h1>Search Movies</h1>
<input type="text" id="movieInput" onkeyup="fetchMovies()"
placeholder="Start typing a movie name..." />
<div id="results"></div>
</body>
</html>
7. Run the Server & Test
python manage.py runserver
Visit http://127.0.0.1:8000/, type 3+ letters into the search box, and see results
appear live via AJAX.
User Interface:
| Search Movies |
| Start typing a movie name... |
| [user types: "sta"] |
Search Results:
- Star Wars
- Star Trek
- Stargate
How it Works:
• When the user types "sta", an AJAX request is sent to
/ajax/search/?query=sta.
• Django returns a JSON list: ["Star Wars", "Star Trek", "Stargate"].
• JavaScript parses the JSON and injects an HTML list
(<ul><li>...</li></ul>) into the #results div.
****************************************************************