Start project and app

  • No need of creating new virtual environment, If there exist a previously created virtual environment just activate it and follow the below steps.
  • start a new django project django-admin startproject models_demo, enter into that directory cd models_demo and open VScode in that directory code .

VScode part

  • In VS code open terminal and start a new app python3 manage.py startapp models_app.
  • Register this app in settings.py file. Open settings.py and goto Installed apps section and add app name models_app in the list.

Edit urls.py file in models_demo

  • edit that file as shown below.
from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include("models_app.urls"))
]
        

Creat a models

  • goto models_app folder and edit model.py file
  • models_app->models.py

from django.db import models

# Create your models here.
class Student(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField(unique=True)

    def __str__(self):
        return self.name

class Course(models.Model):
    title = models.CharField(max_length=200)
    students = models.ManyToManyField(Student, related_name='courses', blank=True)

    def __str__(self):
        return self.title
        

Register the models in admin.py file

  • models_app->admin.py

from django.contrib import admin
from models_app.models import Student,Course

# Register your models here.
admin.site.register(Student)
admin.site.register(Course)
        

Create a templates folder and add html files

  • create a templates folder at models_demo project folder not in the app.
  • Register this templates folder in settings.py.
  • In models_demo->settings.py add this line 'DIRS':[BASE_DIR,templates'],
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR,'templates'], # <----------------- add here.
        'APP_DIRS': True,
        # rest of the code #
            ...
        
  • Now in templates folder add these html files register.html and registered.html
  • register.html
<!DOCTYPE html>
<head>
    <title>Register Student to Course</title>
</head>
<body>
    <h2>Register Student</h2>
    <form method="post" action="{% url 'register' %}">
        {% 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>
    {% if messages %}
        <ul class="messages">
            {% for message in messages %}
                 <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
            {% endfor %}
        </ul>
    {% endif %}

    <!-- 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>

    <script>
        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>

</body>
</html>
        
  • registered.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Registered Students</title>
</head>
<body>
    <h2>Registered Students for {{ course.title }}</h2>
    <ul>
        {% for student in students %}
            <li>{{ student.name }} - {{ student.email }}</li>
        {% empty %}
            <li>No students registered for this course yet.</li>
        {% endfor %}
    </ul>
</body>
</html>
        

Write views to render these html files.

  • models_app->views.py
from django.shortcuts import render, redirect, HttpResponse, get_object_or_404
from django.contrib import messages
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)
        messages.success(request, 'Student successfully added to the course.')
        return redirect('register')
    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})
        

Set urls.py in models_app app.

  • models_app->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'),
]
      

Creating super user and making migrations.

  • Before we create a super user we should make migrations and migrate the contents.
  • now in terminal enter python3 manage.py makemigrations.
  • after making migrations migrate it with this command python3 manage.py migrate.
  • Now create a super-user.
  • In terminal enter python3 manage.py createsuperuser
  • enter required credentials.
  • Run python3 manage.py runserver.

Admin panel

  • go to admin panel and enter required credentials and log in to it.
  • In courses add some courses for students to register.

Registering for courses

  • enter this url http://localhost:8000/register/.
  • enter the fields, select the course and hit the register button.
  • you should see registration successful message.

Viewing the registered students for particular subject

  • In the same page enter the course title field (the course should exist, don't enter course which is not created) and hit enter.
  • you should see all the registered students for that subject.

We can perform the same in the admin panel by directly adding the contents to it.

Resourses

Watch a quick video summary on how to run this program

Watch it at 2x speed