Create a generic class view to display a list of students and a detail view that displays student details for any selected student

Create a generic class view to display a list of students and a detail view that displays student details for any selected student

Program:-

views.py:-

from django.views import generic
from .models import Student

class StudentListView(generic.ListView):
    model = Student
    template_name = "student_list.html"
    context_object_name = "student_list"

class StudentDetailView(generic.DetailView):
    model = Student
    template_name = "student_detail.html"

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="{% url 'student_detail' pk=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>

urls.py:-

from django.contrib import admin
from django.urls import path, re_path
from ap3.views import StudentListView, StudentDetailView

admin.site.site_header = "My Site Header"
admin.site.site_title = "My Site Title"
admin.site.index_title = "My Site Index"

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

Leave a Reply

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