loader image

21CS62 Program 7

7. Develop a Django app that performs student registration to a course. It should also display list of students registered for any selected course. Create students and course as models with enrolment as ManyToMany field.

Step-01: Create new folder:-
⦿ In the same project folder whatever we made earlier create again one new app name called as ‘registration’ using below command.

cd project
python manage.py startapp registration

Step-02: Add the ‘registration’ to the installed_apps list:-
⦿ locate the settings.py file (usually located in the project directory) and open it.
⦿After then add your app name in install_apps list as per below image.

vscode

Step-03: Inside models.py file create a model:-

from django.db import models

class Course(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()

    def __str__(self):
        return self.name

    @property
    def student_count(self):
        return self.students.count()

class Student(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.EmailField(unique=True, null=True)
    phone_number = models.CharField(max_length=15, null=True)
    courses = models.ManyToManyField(Course, related_name='students', through='Enrollment')

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

class Enrollment(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE)
    course = models.ForeignKey(Course, on_delete=models.CASCADE)
    enrolled_on = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.student} enrolled in {self.course}"
vscode

Step-04: Run the below command to create the model:-

python manage.py makemigrations
python manage.py migrate

Step-05: Create forms.py file inside the ‘registration’ folder:-

⦿ Open the forms.py file in your Django project directory (registration/forms.py).
⦿ Create a new form that will handle the request using below command.

from django import forms
from .models import Student, Course

class StudentForm(forms.ModelForm):
    class Meta:
        model = Student
        fields = ['first_name', 'last_name', 'email', 'phone_number', 'courses']

class CourseForm(forms.ModelForm):
    class Meta:
        model = Course
        fields = ['name', 'description']
vscode

Step-06: Inside views.py file create a function:-
⦿ Open the views.py file in your Django project directory (registration/views.py).
⦿ Import the required modules at the top of the file.
⦿ Create a new view function that will handle the request and display the data in the templates.

from django.shortcuts import render, redirect
from .models import Student, Course
from .forms import StudentForm, CourseForm

def register_student(request):
    if request.method == 'POST':
        form = StudentForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('student_list')
    else:
        form = StudentForm()
    return render(request, 'register_student.html', {'form': form})

def register_course(request):
    if request.method == 'POST':
        form = CourseForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('course_list')
    else:
        form = CourseForm()
    return render(request, 'register_course.html', {'form': form})

def student_list(request):
    students = Student.objects.all()
    return render(request, 'student_list.html', {'students': students})

def course_list(request):
    courses = Course.objects.all()
    return render(request, 'course_list.html', {'courses': courses})
vscode

Step-07: Create a template:-
⦿ Right click on ‘registration’ folder, create a new folder named templates.
⦿ Inside the templates folder, create a new file named base.html.
⦿ Inside the templates folder, create a new file named register_student.html.
⦿ Inside the templates folder, create a new file named register_course.html.
⦿ Inside the templates folder, create a new file named student_list.html.
⦿ Inside the templates folder, create a new file named course_list.html.
⦿ Copy all the different different html file code and paste into all different html file to display the user interface.

base.html

<!DOCTYPE html>
<html>
<head>
    <title>Student and Course Registration</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f9;
            color: #333;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }
        nav {
            position: sticky;
            background-color: #4CAF50;
            padding: 15px;
            text-align: center;
        }
        nav a {
            color: white;
            text-decoration: none;
            margin: 0 15px;
            font-size: 16px;
        }
        nav a:hover {
            text-decoration: underline;
        }
        hr {
            border: 0;
            height: 1px;
            background: #ddd;
            margin: 20px 0;
        }

        p {
            margin: 0;
        }
        .container {
            width:40%;
            margin: 20px auto;
            background-color: white;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            border-radius: 7px;
            flex: 1;
        }

        .content h2 {
            color: #fff;
            background: #000;
            padding: 5px;
            border-radius: 7px;
            border: 1px solid #000;
            text-align: center;
        }
        .content {
            padding: 20px;
        }
        form {
            display: flex;
            flex-direction: column;
        }
        label {
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"],
        input[type="email"],
        input[type="password"],
        select,
        textarea {
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 7px;
            font-size: 16px;
            width: 100%;
            box-sizing: border-box;
        }

        .content li {
            border-radius: 7px;
            margin-bottom: 12px;
            padding: 5px;
            border: 1px solid #00000052;
        }

        li {
            list-style: auto;
        }

        input[type="submit"],
        button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 7px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 10px;
        }
        input[type="submit"]:hover,
        button:hover {
            background-color: #45a049;
        }
        .form-section {
            margin-bottom: 20px;
        }

        option {
            margin-bottom: 7px;
            color: #050505;
            border-radius: 7px;
            padding: 3px;
            border: 1px solid #000;
        }

        #id_courses {
            overflow-y: scroll;
        }
        footer {
            background-color: #4CAF50;
            color: white;
            text-align: center;
            padding: 15px 0;
        }
    </style>
</head>
<body>
    <nav>
        <a href="{% url 'register_student' %}">Register Student</a> |
        <a href="{% url 'register_course' %}">Register Course</a> |
        <a href="{% url 'student_list' %}">Student List</a> |
        <a href="{% url 'course_list' %}">Course List</a> |
    </nav>
    <div class="container">
        <div class="content">
            {% block content %}
            {% endblock %}
        </div>
    </div>
    <footer>
        Designed by Braham Copyright © vtucode | All rights reserved.
    </footer>
</body>
</html>

register_student.html

{% extends 'base.html' %}

{% block content %}
<h2>Register Student</h2>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Register</button>
</form>
{% endblock %}

register_course.html

{% extends 'base.html' %}

{% block content %}
<h2>Register Course</h2>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Register</button>
</form>
{% endblock %}

student_list.html

{% extends 'base.html' %}

{% block content %}
<h2>Student List</h2>
{% if students %}
    <ul>
        {% for student in students %}
        <li>{{ student.first_name }} {{ student.last_name }}</li>
        {% endfor %}
    </ul>
{% else %}
    <p>No students are registered.</p>
{% endif %}
{% endblock %}

course_list.html

{% extends 'base.html' %}

{% block content %}
<h2>Course List</h2>
{% if courses %}
    <ul>
        {% for course in courses %}
        <li>{{ course.name }} → {{ course.student_count }} students enrolled</li>
        {% endfor %}
    </ul>
{% else %}
    <p>No courses are available.</p>
{% endif %}
{% endblock %}

Step-08: Add URLs path in the project’s URL patterns:-
⦿ Open the file in your Django project directory (project/urls.py).
⦿ Import the view function at the top of the file.
⦿ Add new URL pattern to the urlpatterns list.

from django.urls import path
from registration import views

urlpatterns = [
    path('', views.register_student, name='register_student'),
    path('register_course/', views.register_course, name='register_course'),
    path('student_list/', views.student_list, name='student_list'),
    path('course_list/', views.course_list, name='course_list'),
]
Screenshot 267

Step-9: Run Your Project:-
⦿ Now setup is completed you can run your project using below command.
⦿ The terminal will display the URL where the development server is running, typically http://127.0.0.1:8000/.
⦿ Copy the URL from the terminal and paste it into your web browser’s address bar to see the output web page.

python manage.py runserver
Screenshot 272 1
output
output
output

Leave a Reply

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