Caching views

You can cache the output of individual views using the cache_page decorator located at django.views.decorators.cache. The decorator requires a timeout argument (in seconds).

Let's use it in our views. Edit the urls.py file of the students application and add the following import:

from django.views.decorators.cache import cache_page

Then, apply the cache_page decorator to the student_course_detail and student_course_detail_module URL patterns, as follows:

path('course/<pk>/',     cache_page(60 * 15)(views.StudentCourseDetailView.as_view()),     name='student_course_detail'),path('course/<pk>/<module_id>/',     cache_page(60 * 15)(views.StudentCourseDetailView.as_view()),     name='student_course_detail_module'),

Now, the result for the StudentCourseDetailView ...

Get Django 2 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.