Program 8

For students enrolment developed in Module 2, create a generic class view which displays list of students and detailview that displays student details for any selected student in the list.

views.py

from django.shortcuts import render
from django.views import generic
from .models import Student

# Create your views here.
class StudentListView(generic.ListView):
    model=Student
    template_name="student_list.html"
    
class StudentDetailView(generic.DetailView):
    model=Student
    template_name="student_detail.html"

urls.py

from django.urls import path
from .views import StudentDetailView,StudentListView

urlpatterns = [
    path('student_list/', StudentListView.as_view()),
    path('student_detail/<int:pk>/', StudentDetailView.as_view()),
]

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)
    

admin.py

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

admin.site.register(Student)
admin.site.register(Course)

templates/student_list.html

<html>
  <body>
    {% if student_list %}
    <table border>
      <tr>
        <th>USN</th>
        <th>Courses Enrolled</th>
      </tr>
      {% for student in student_list %}
      <tr>
        <td>
          <a href="/p9/student_detail/{{student.pk}}">
            {{ student.student_usn }}
          </a>
        </td>

        <td>
          {% for course in student.enrolment.all %}
          <span>{{ course.course_name }}</span>
          {% endfor %}
        </td>
      </tr>
      {% endfor %}
    </table>
    {% else %}
    <h1>No Students Enrolled</h1>
    {% endif %}
  </body>
</html>

templates/student_detail.html

<h1>Student Name: {{ student.student_name }}</h1>
<h1>Student USN: {{ student.student_usn }}</h1>
<h1>Student Sem: {{ student.student_sem }}</h1>