How to Use Template Fragment Caching in Django Efficiently
Use Django's
{% cache %} template tag to cache parts of your template by wrapping the fragment you want to cache with {% cache timeout cache_key %} and {% endcache %}. This stores the rendered fragment for the specified timeout in seconds, improving performance by avoiding repeated rendering.Syntax
The {% cache %} tag caches a template fragment. It requires two arguments: timeout (in seconds) and a cache key to identify the cached fragment uniquely.
Example parts:
timeout: How long to keep the cache (e.g., 600 for 10 minutes).cache_key: A unique string or variable to identify the cached fragment.
Wrap the template code you want to cache between {% cache %} and {% endcache %}.
django
{% cache 600 sidebar %}
... template code to cache ...
{% endcache %}Example
This example caches a sidebar fragment for 5 minutes. The cache key is sidebar. When the page renders, Django stores the sidebar HTML in cache and reuses it until 5 minutes pass.
django
{% load cache %}
<div class="sidebar">
{% cache 300 sidebar %}
<h3>Popular Posts</h3>
<ul>
{% for post in popular_posts %}
<li>{{ post.title }}</li>
{% endfor %}
</ul>
{% endcache %}
</div>Output
<div class="sidebar">
<h3>Popular Posts</h3>
<ul>
<li>Post 1</li>
<li>Post 2</li>
<li>Post 3</li>
</ul>
</div>
Common Pitfalls
- Forgetting to
{% load cache %}at the top of the template causes the{% cache %}tag to fail. - Using a static cache key without variables can cause stale content if the fragment depends on dynamic data.
- Not setting a proper timeout can lead to very old cached content or frequent cache misses.
- Cache backend must be configured in Django settings; otherwise, caching won't work.
django
{% load cache %}
{# Wrong: static cache key for user-specific content #}
{% cache 600 sidebar %}
Hello, {{ user.username }}!
{% endcache %}
{# Right: include user id in cache key #}
{% cache 600 sidebar user.id %}
Hello, {{ user.username }}!
{% endcache %}Quick Reference
Remember these tips for template fragment caching:
- Always
{% load cache %}before using the tag. - Use unique cache keys, including variables if needed.
- Set a sensible timeout in seconds.
- Ensure your Django cache backend is properly configured.
Key Takeaways
Use {% cache timeout cache_key %} ... {% endcache %} to cache template parts in Django.
Always load the cache tag library with {% load cache %} before using caching tags.
Include dynamic variables in cache keys to avoid serving stale or incorrect content.
Set an appropriate timeout to balance freshness and performance.
Configure Django's cache backend properly for caching to work.