0
0
Djangoframework~30 mins

Per-view caching in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Implementing Per-view Caching in Django
📖 Scenario: You are building a simple Django web application that shows a list of products. To improve performance, you want to cache the output of the product list page so that repeated visits load faster.
🎯 Goal: Learn how to add per-view caching to a Django view function to speed up page loading by storing the rendered response for a set time.
📋 What You'll Learn
Create a Django view function called product_list that returns a simple HTTP response.
Add a cache timeout variable called CACHE_TTL set to 60 seconds.
Apply the @cache_page decorator with CACHE_TTL to the product_list view.
Ensure the final code includes the necessary import for cache_page and the view returns the expected response.
💡 Why This Matters
🌍 Real World
Per-view caching is used in web applications to speed up page loading by storing the output of views temporarily. This reduces server load and improves user experience.
💼 Career
Understanding per-view caching is important for backend developers working with Django to optimize web application performance and scalability.
Progress0 / 4 steps
1
Create the product_list view function
Create a Django view function called product_list that returns an HttpResponse with the text "Product list page". Import HttpResponse from django.http.
Django
Need a hint?

Remember to define a function named product_list that takes request as a parameter and returns HttpResponse("Product list page").

2
Add a cache timeout variable CACHE_TTL
Add a variable called CACHE_TTL and set it to 60 to represent the cache timeout in seconds.
Django
Need a hint?

Define CACHE_TTL = 60 above the view function.

3
Import and apply the @cache_page decorator
Import cache_page from django.views.decorators.cache. Then apply the @cache_page(CACHE_TTL) decorator above the product_list view function.
Django
Need a hint?

Use @cache_page(CACHE_TTL) just above the def product_list(request): line.

4
Complete the view with caching applied
Ensure the final code includes the import of HttpResponse, the import of cache_page, the CACHE_TTL variable set to 60, and the product_list view decorated with @cache_page(CACHE_TTL) returning the correct response.
Django
Need a hint?

Check that all parts are present and the view is decorated correctly.