- Again we need the Student registration project from module 2.
- If you want to create it again and alter it for this program follow the instructions in the programs lists student list of this website.
- Or you can directly download that project and make changes in it.
- Alter the below files in this project.
urls.py
from django.urls import path, include
from . import views
urlpatterns = [
path('test/', views.test, name="test"),
path('register/', views.register, name="register"),
path('registered/<str:course_title>/', views.registered, name='registered'),
path('search_student_courses/', views.search_student_courses, name='search_student_courses'),
]
views.py
from django.shortcuts import render, redirect, HttpResponse, get_object_or_404
from django.contrib import messages
from django.http import JsonResponse
from .models import Student, Course
# Create your views here.
def test(request):
return HttpResponse("this is a test")
def register(request):
if request.method == 'POST':
student_name = request.POST['name']
student_email = request.POST['email']
course_id = request.POST['course']
course = Course.objects.get(pk=course_id)
student, created = Student.objects.get_or_create(name=student_name, email=student_email)
course.students.add(student)
return JsonResponse({'message': 'Student successfully added to the course.'})
else:
courses = Course.objects.all()
return render(request, 'register.html', {'courses': courses})
def registered(request, course_title):
course = get_object_or_404(Course, title=course_title)
students = course.students.all()
return render(request, 'registered.html', {'course': course, 'students': students})
def search_student_courses(request):
if request.method == 'POST':
student_name = request.POST['student_name_search']
student = get_object_or_404(Student, name=student_name)
courses = student.courses.values_list('title', flat=True)
return JsonResponse({'courses': list(courses)})
return JsonResponse({'error': 'Invalid request'}, status=400)
register.html
<!DOCTYPE html>
<head>
<title>Register Student to Course</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h2>Register Student</h2>
<form id="registerForm">
{% csrf_token %}
<label for="name">Name:</label>
<input type="text" id="name" name="name" maxlength="50" required>
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br>
<label for="course">Select Course:</label>
<select id="course" name="course" required>
{% for course in courses %}
<option value="{{ course.id }}">{{ course.title }}</option>
{% endfor %}
</select>
<br>
<button type="submit">Register</button>
</form>
<div id="registerResult"></div>
<!-- Let the students view who all opted for particular course by selecting the course -->
<form id="redirectForm" method="get" onsubmit="redirectToRegisteredStudents(event)">
<label for="course_title">Enter Course Title:</label>
<input type="text" id="course_title" name="course_title" required>
<button type="submit">Go</button>
</form>
<!-- Search for a student to view their courses -->
<h2>Search Student's Enrolled Courses</h2>
<form id="searchForm">
{% csrf_token %}
<label for="student_name_search">Enter Student Name:</label>
<input type="text" id="student_name_search" name="student_name_search" required>
<button type="submit">Search</button>
</form>
<div id="searchResult"></div>
<script>
// AJAX for registration
$('#registerForm').submit(function(event) {
event.preventDefault();
$.ajax({
url: "{% url 'register' %}",
type: 'POST',
data: $(this).serialize(),
success: function(response) {
$('#registerResult').html('<p>' + response.message + '</p>');
},
error: function(xhr) {
$('#registerResult').html('<p>An error occurred.</p>');
}
});
});
// AJAX for searching student's enrolled courses
$('#searchForm').submit(function(event) {
event.preventDefault();
$.ajax({
url: "{% url 'search_student_courses' %}",
type: 'POST',
data: $(this).serialize(),
success: function(response) {
if (response.courses.length > 0) {
var coursesList = '<ul>';
for (var i = 0; i < response.courses.length; i++) {
coursesList += '<li>' + response.courses[i] + '</li>';
}
coursesList += '</ul>';
$('#searchResult').html(coursesList);
} else {
$('#searchResult').html('<p>No courses found for this student.</p>');
}
},
error: function(xhr) {
$('#searchResult').html('<p>An error occurred.</p>');
}
});
});
<!-- to show student details based on the course input -->
function redirectToRegisteredStudents(event) {
event.preventDefault(); // Prevent the default form submission
var courseTitle = document.getElementById('course_title').value;
if (courseTitle) {
// Encode the course title to be URL safe
var encodedCourseTitle = encodeURIComponent(courseTitle);
// Redirect to the desired URL
window.location.href = '/registered/' + encodedCourseTitle + '/';
}
}
</script>
</body>
</html>
See the output
- run
python manage.py runserver
- go to this url
http://localhost:8000/register/
- Register some students.
- Check the students opted courses by entering their name.
- If you see in your local server running terminal you'll see "HTTP POST parameters that are sent to your view without loading the page"
Resourses
- w3schools
- jQuery.ajax() | jQuery API Documentation