0
0
Djangoframework~30 mins

Template fragment caching in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Django Template Fragment Caching
📖 Scenario: You are building a blog page in Django. Some parts of the page, like the list of recent posts, do not change often. To make the page load faster, you want to save (cache) that part of the page so Django can reuse it without rebuilding every time.
🎯 Goal: Learn how to use Django's template fragment caching to save and reuse parts of a template for faster page loading.
📋 What You'll Learn
Create a Django template with a list of recent posts
Add a cache timeout variable in the template context
Use the cache template tag to cache the recent posts fragment
Set the cache timeout using the variable
💡 Why This Matters
🌍 Real World
Caching parts of a web page helps websites load faster by reusing content that does not change often.
💼 Career
Knowing how to use Django's template fragment caching is useful for web developers to optimize performance and improve user experience.
Progress0 / 4 steps
1
Create the recent posts list in the template
In your Django template, create an unordered list with the class recent-posts. Inside it, add three list items with the exact text: Post 1, Post 2, and Post 3.
Django
Need a hint?

Use <ul> with class recent-posts and three <li> items with the exact post names.

2
Add a cache timeout variable in the template context
In your Django view, create a variable called cache_timeout and set it to 300 (seconds). This variable will control how long the cache lasts.
Django
Need a hint?

Just create a variable named cache_timeout and assign it the value 300.

3
Wrap the recent posts list with the cache template tag
In your Django template, wrap the <ul class="recent-posts"> block with the {% cache %} template tag. Use the cache key 'recent_posts' and the timeout variable cache_timeout. The syntax is {% cache cache_timeout 'recent_posts' %} before the list and {% endcache %} after.
Django
Need a hint?

Use {% cache cache_timeout 'recent_posts' %} before the list and {% endcache %} after it. Also add {% load cache %} at the top.

4
Complete the template fragment caching setup
Make sure the template starts with {% load cache %} to enable caching tags. Confirm the cache block uses the key 'recent_posts' and the timeout variable cache_timeout. The cache block should wrap the entire <ul> list.
Django
Need a hint?

Check that {% load cache %} is at the top and the cache block wraps the list with the correct key and timeout.