I want to use django fragment caching for anonymous users, but give authenticated users fresh data. This seems to work fine:
{% if user.is_anonymous %}
{% load cache %}
{% cache 300 "my-cache-fragment" %}
<b>I have to write this out twice</b>
{% endcache %}
{% else %}
<b>I have to write this out twice</b>
{% endif %}
The only problem is that I have to repeat the html to be cached. Is there some clever way around this, other than putting it in an include? Thanks.
Try setting the cache timeout to zero for authenticated users.
views.py:
context = {
"cache_timeout": 300 if request.user.is_anonymous() else 0,
}
Template:
{% load cache %}
{% cache cache_timeout "my-cache-fragment" %}
<b>I have to write this only once</b>
{% endcache %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With