For our course catalog, we have to build the following functionality:
- List all available courses, optionally filtered by subject
- Display a single course overview
Edit the views.py file of the courses application and add the following code:
from django.db.models import Countfrom .models import Subjectclass CourseListView(TemplateResponseMixin, View): model = Course template_name = 'courses/course/list.html' def get(self, request, subject=None): subjects = Subject.objects.annotate( total_courses=Count('courses')) courses = Course.objects.annotate( total_modules=Count('modules')) if subject: subject = get_object_or_404(Subject, slug=subject) courses = courses.filter(subject=subject) return self.render_to_response({'subjects': ...