Develop a Django app for student registration to a course and display a list of students registered for any selected course
Programs:-
models.py:-
# models.py from django.db import models # Create your models here. class Course(models.Model): course_code = models.CharField(max_length=40) course_name = models.CharField(max_length=100) course_credits = models.IntegerField() class Student(models.Model): student_usn = models.CharField(max_length=20) student_name = models.CharField(max_length=100) student_sem = models.IntegerField() enrolment = models.ManyToManyField(Course)
templates/reg.html:-
<!-- reg.html inside templates folder --> <html> <body> <form method="post" action=""> {% csrf_token %} Student Name <select name="sname"> {% for student in students %} <option value="{{ student.id }}">{{ student.student_name }}</option> {% endfor %} </select><br> Course Name <select name="cname"> {% for course in courses %} <option value="{{ course.id }}">{{ course.course_name }}</option> {% endfor %} </select><br> <input type="submit" value="Enroll"> </form> </body> </html>
views.py:
from django.http import HttpResponse from django.shortcuts import render from ap3.models import Course, Student def reg(request): if request.method == "POST": sid = request.POST.get("sname") cid = request.POST.get("cname") student = Student.objects.get(id=sid) course = Course.objects.get(id=cid) res = student.enrolment.filter(id=cid) if res: return HttpResponse("<h1>Student already enrolled</h1>") student.enrolment.add(course) return HttpResponse("<h1>Student enrolled successfully</h1>") else: students = Student.objects.all() courses = Course.objects.all() return render(request, "reg.html", {"students": students, "courses": courses})
urls.py:-
# urls.py from django.contrib import admin from ap3.views import reg urlpatterns = [ path('admin/', admin.site.urls), path('reg/', reg), ]
admin.py:
from django.contrib import admin from .models import Student, Course # Register your models here. admin.site.register(Student) admin.site.register(Course)
cmd:
py manage.py makemigrations py manage.py migrate python manage.py createsuperuser python manage.py runserver