Lab 51
Lab 51
py
from django.shortcuts import render
from django.http import JsonResponse
from .forms import StudentRegistrationForm
def register_student(request):
if request.method == 'POST':
form = StudentRegistrationForm(request.POST)
if form.is_valid():
# Here you would typically save the data to a database or perform other actions
return JsonResponse({"success": True, "message": "Student registered
successfully!"})
else:
return JsonResponse({"success": False, "errors": form.errors})
else:
form = StudentRegistrationForm()
return render(request, 'enrollment/register.html', {'form': form})
#urls.py (enrollment/urls.py)
from django.urls import path
from .views import register_student
urlpatterns = [
path('register/', register_student, name='register_student'),
]
#urls.py (myproject/urls.py)
…
path('', include('enrollment.urls')),
…
#forms.py
from django import forms
class StudentRegistrationForm(forms.Form):
name = forms.CharField(label='Full Name', max_length=100)
email = forms.EmailField(label='Email')
course = forms.CharField(label='Course', max_length=100)
#register.html (enrollment/templates/enrollment/register.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Registration</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<form id="registrationForm">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>
<div id="message"></div>
<script>
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
$(document).ready(function () {
$('#registrationForm').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url "register_student" %}',
data: $(this).serialize(),
success: function (response) {
if (response.success) {
$('#message').html('<p style="color: green;">' + response.message + '</p>');
$('#registrationForm').trigger('reset'); // Reset form if needed
} else {
$('#message').html('<p style="color: red;">' + JSON.stringify(response.errors) +
'</p>');
}
}
});
});
});
</script>
</body>
</html>