10 b] Write a program to develop a search application in Django using AJAX that displays courses enrolled by a student being searched.\
To develop a search application in Django using AJAX that displays courses enrolled by a student being searched, you’ll need to follow these steps:
- Set Up Your Django Project and Application
- Create Models for Students and Courses
- Create Views and Templates
- Add AJAX Functionality
- Update URLs
Here’s a step-by-step guide with code examples:
1. Set Up Your Django Project and Application
First, ensure you have Django installed and create a new project and app.
django-admin startproject myproject cd myproject python manage.py startapp search
2. Create Models for Students and Courses
In search/models.py, define the models for Student and Course. You may need a Student model and a Course model, and a many-to-many relationship between them.
# search/models.py
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Course(models.Model):
title = models.CharField(max_length=100)
students = models.ManyToManyField(Student, related_name='courses')
def __str__(self):
return self.titleRun migrations to create these models in the database:
python manage.py makemigrations python manage.py migrate
3. Create Views and Templates
Create a view to handle the AJAX request and return the course data. In search/views.py:
# search/views.py
from django.http import JsonResponse
from .models import Student
def search_courses(request):
student_name = request.GET.get('name', '')
try:
student = Student.objects.get(name=student_name)
courses = list(student.courses.values('title'))
return JsonResponse({'courses': courses})
except Student.DoesNotExist:
return JsonResponse({'courses': []})Create a template for the search form and display results. In search/templates/search/search.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Search Courses</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Search Courses by Student</h1>
<input type="text" id="studentName" placeholder="Enter student name">
<button id="searchBtn">Search</button>
<h2>Courses:</h2>
<ul id="courseList"></ul>
<script>
$(document).ready(function() {
$('#searchBtn').click(function() {
var name = $('#studentName').val();
$.ajax({
url: '/search-courses/',
data: {
'name': name
},
dataType: 'json',
success: function(data) {
var courseList = $('#courseList');
courseList.empty();
if (data.courses.length > 0) {
$.each(data.courses, function(index, course) {
courseList.append('<li>' + course.title + '</li>');
});
} else {
courseList.append('<li>No courses found</li>');
}
}
});
});
});
</script>
</body>
</html>4. Add AJAX Functionality
In search/urls.py, add a URL pattern for the AJAX view:
# search/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.search_courses, name='search_courses'),
]Include these URLs in the main myproject/urls.py:
# myproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('search-courses/', include('search.urls')),
]5. Update the Django Admin
You may want to add some students and courses to test your application. Register your models in search/admin.py:
# search/admin.py from django.contrib import admin from .models import Student, Course admin.site.register(Student) admin.site.register(Course)
Now you can run your Django development server:
python manage.py runserver
Navigate to http://127.0.0.1:8000/ in your browser. You should see the search form where you can enter a student’s name, and upon clicking “Search,” the courses they are enrolled in will be displayed dynamically.
This setup provides a basic implementation of an AJAX search application in Django. You can further enhance it by adding error handling, improving the UI, or extending the functionality as needed.
