21CS62 Program 10

10. 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
from django.views.generic import ListView, DetailView

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})


class StudentListView(ListView):
    model = Student
    template_name = 'student_list.html'
    context_object_name = 'students'
    
    
class CourseListView(ListView):
    model = Course
    template_name = 'course_list.html'
    context_object_name = 'courses'
    

class StudentDetailView(DetailView):
    model = Student
    template_name = 'student_detail.html'
    context_object_name = 'student'


class CourseDetailView(DetailView):
    model = Course
    template_name = 'course_detail.html'
    context_object_name = 'course'
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.
⦿ Inside the templates folder, create a new file named student_detail.html.
⦿ Inside the templates folder, create a new file named course_detail.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>

        *{
            padding:0;
            margin:0;
            box-sizing:border-box;
        }

        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 {
            font-weight: 600;
            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:35%;
            margin: 34.7px auto;
            background-color: white;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            border-radius: 7px;
        }

        .content h2,h1 {
            margin-bottom: 20px;
            font-size:22px;
            color: #fff;
            background: #000;
            padding: 9px;
            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;
        }

        #note {
            color: red;
        }

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

        .content li a{
            text-decoration: none;
            color: #0a00ff;
        }

        .content li a:hover{
            text-decoration: underline;
        }


        li {
            list-style: none;
        }

        input[type="submit"],
        button {
            font-weight: 600;
            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 {
            font-weight: 600;
            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 %}
  <h1>Student List</h1>
  {% if students  %}
  <ul>
    {% for student in students %}
      <li><a href="{% url 'student_detail' student.pk %}">{{ student.first_name }}</a></li>
    {% endfor %}
  </ul>
  {% else %}
    <p id="note">No student registered at the moment...</p>
  {% endif %}
{% endblock %}

course_list.html

{% extends 'base.html' %}

{% block content %}
  <h1>Course List</h1>
  {% if courses %}
    <ul>
      {% for course in courses %}
        <li><a href="{% url 'course_detail' course.pk %}">{{ course.name }}</a></li>
      {% endfor %}
    </ul>
  {% else %}
    <p id="note">No course registered at the moment...</p>
  {% endif %}
{% endblock %}

student_detail.html

{% extends 'base.html' %}

{% block content %}
  <h1>Student Details</h1>
  <p><b>Name:</b> {{ student.first_name }} {{ student.last_name }}</p>
  <p><b>Email:</b> {{ student.email }}</p>
  <p><b>Phone:</b> {{ student.phone_number }}</p>
  <p><b>Course:</b>
  
    {% for course in student.courses.all %}
       {{ course.name }} </p>
    {% endfor %}
  
{% endblock %}

course_detail.html

{% extends 'base.html' %}

{% block content %}
  <h1>Course Details</h1>
    <p><b>Name:</b> {{ course.name }}</p>
    <p><b>Description:</b> {{ course.description }}</p>
{% 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
from registration.views import StudentListView, StudentDetailView, CourseDetailView, CourseListView

urlpatterns = [
    path('', views.register_student, name='register_student'),
    path('register_course/', views.register_course, name='register_course'),
    path('students/', StudentListView.as_view(), name='student_list'),
    path('students/<pk>/', StudentDetailView.as_view(), name='student_detail'),
    path('courses/', CourseListView.as_view(), name='course_list'),
    path('courses/<pk>/', CourseDetailView.as_view(), name='course_detail'),
]
vscode

Step-09: 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
output
output
output
Screenshot 298
output
output

Leave a Reply

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