Develop a search application in Django using AJAX that displays courses enrolled by a student being searched

Develop a search application in Django using AJAX that displays courses enrolled by a student being searched

Program:-

views.py:-

from django.http import HttpResponse
from django.shortcuts import render
from ap3.models import Course, Student

def course_search_ajax(request):
    if request.method == "POST":
        cid = request.POST.get("cname")
        s = Student.objects.all()
        student_list = []
        for student in s:
            if student.enrolment.filter(id=cid).exists():
                student_list.append(student)
        if len(student_list) == 0:
            return HttpResponse("<h1>No Students enrolled</h1>")
        return render(request, "selected_students.html", {"student_list": student_list})
    else:
        courses = Course.objects.all()
        return render(request, "course_search_aj.html", {"courses": courses})

templates/course_search_aj.html:-

{% load static %}
<html>
<body>
<form method="POST" action="">
    courses
    {% csrf_token %}
    <select name="cname" id="cname">
        {% for course in courses %}
        <option value="{{ course.id }}">{{ course.course_name }}</option>
        {% endfor %}
    </select>
    <input type="button" value="Search" id="serbtn">
    <span id="result"></span>
</form>
</body>
<script src="{% static 'jquery.min.js' %}"></script>
<script>
$(document).ready(function(){
    $("#serbtn").click(function(){
        var cname = $("#cname").val();
        $.ajax({
            url: "/course_search_ajax/",
            type: "POST",
            data: { cname: cname, csrfmiddlewaretoken: "{{ csrf_token }}" },
            success: function(response){
                $("#result").html(response);
            }
        });
    });
});
</script>
</html>

urls.py:-

from django.contrib import admin
from django.urls import path
from ap3.views import expr, cbox, regaj, course_search_ajax, cookie_demo

admin.site.site_header = "My Site Header"
admin.site.site_title = "My Site Title"
admin.site.index_title = "My Site Index"

urlpatterns = [
    path('secretadmin/', admin.site.urls),
    path('course_search_ajax/', course_search_ajax),
]

Leave a Reply

Your email address will not be published. Required fields are marked *