0% found this document useful (0 votes)
4 views

Ajax 2

Uploaded by

Srihari Murali
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Ajax 2

Uploaded by

Srihari Murali
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 6

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,
you'll need to follow these steps:

### 1. Set up a Django Project and App

If you haven't already set up your Django project and app, follow the steps mentioned earlier to
create a new Django project (`enrollment_project`) and a new app (`enrollment`).

### 2. Define Models

Define your models in `enrollment/models.py`:

```python

from django.db import models

class Student(models.Model):

name = models.CharField(max_length=100)

class Course(models.Model):

name = models.CharField(max_length=100)

students = models.ManyToManyField(Student, related_name='courses')

```

### 3. Set up URLs

Configure URLs in `enrollment/urls.py` to handle search requests:

```python

from django.urls import path

from . import views


urlpatterns = [

path('', views.home, name='home'),

path('search/', views.search_student_courses, name='search_student_courses'),

```

### 4. Write Views

Define views in `enrollment/views.py` to handle rendering the home page and processing AJAX
requests:

```python

from django.shortcuts import render

from django.http import JsonResponse

from .models import Student

def home(request):

return render(request, 'enrollment/home.html')

def search_student_courses(request):

if request.is_ajax():

student_name = request.GET.get('student_name', None)

if student_name:

try:

student = Student.objects.get(name__icontains=student_name)

courses = student.courses.all()

course_names = [course.name for course in courses]

return JsonResponse({'courses': course_names})

except Student.DoesNotExist:

return JsonResponse({'error': 'Student not found.'}, status=404)


else:

return JsonResponse({'error': 'Student name is required.'}, status=400)

else:

return JsonResponse({}, status=400)

```

### 5. Create Templates

Create templates to render the search form and handle AJAX responses.

- **Template `enrollment/templates/enrollment/home.html`**:

```html

<!DOCTYPE html>

<html>

<head>

<title>Student Course Search</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

</head>

<body>

<h2>Search for Student Courses</h2>

<form id="searchForm">

<input type="text" id="studentName" name="studentName" placeholder="Enter student name">

<button type="submit">Search</button>

</form>

<div id="courseList">

<!-- Courses will be displayed here -->

</div>
<script>

$(document).ready(function() {

$('#searchForm').submit(function(e) {

e.preventDefault();

var studentName = $('#studentName').val();

$.ajax({

type: 'GET',

url: '/search/',

data: {

'student_name': studentName

},

success: function(response) {

$('#courseList').empty();

if ('error' in response) {

$('#courseList').html('<p>' + response.error + '</p>');

} else {

var courses = response.courses;

if (courses.length > 0) {

var html = '<ul>';

$.each(courses, function(index, course) {

html += '<li>' + course + '</li>';

});

html += '</ul>';

$('#courseList').html(html);

} else {

$('#courseList').html('<p>No courses found for this student.</p>');

}
},

error: function(response) {

$('#courseList').html('<p>Error: Unable to retrieve data.</p>');

});

});

});

</script>

</body>

</html>

```

### Explanation:

- **Views (`enrollment/views.py`)**:

- `home`: Renders the home page (`home.html`) which contains the search form.

- `search_student_courses`: Handles AJAX GET requests to search for courses enrolled by a student
based on their name. Responds with JSON containing course names.

- **Template (`enrollment/templates/enrollment/home.html`)**:

- Includes a form (`searchForm`) that submits via AJAX to `/search/`.

- Uses jQuery for AJAX submission and updates the `#courseList` div based on the response from
the server.

### 6. Configure URLs and Run the Server

Include your app's URLs in the project's `urls.py` (`enrollment_project/urls.py`), and make sure to
include `'enrollment'` in your `INSTALLED_APPS` in `settings.py`.

### 7. Run the Server


Run your Django development server:

```bash

python manage.py runserver

```

Navigate to `http://localhost:8000/` to see the search form. Enter a student's name and click
"Search" to see the courses enrolled by that student displayed dynamically without page refresh
using AJAX.

Adjust the code as per your application's requirements and design preferences.

You might also like