django fragment caching for anonymous users only
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 repea开发者_如何学Pythont 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 %}
{% with cache_timeout=user.is_staff|yesno:"0,300" %}
{% cache cache_timeout cacheidentifier user.is_staff %}
your content here
{% endcache %}
{% endwith %}
Not sure I understand the problem...
{% load cache %}
{% cache 300 "my-cache-fragment" %}
<b>I have to write this out twice</b>
{% endcache %}
{% if not user.is_anonymous %}
<b>And this is the extra uncached stuff for authenticated users</b>
{% endif %}
You can specify caching with passing extra parameters to cache
tag like:
{% cache 500 sidebar request.user.is_anonymous %}
Check here for more info... But this will also cache data for logged-in users too...
Probably you have to write a custom template tag. You can start by inspecting existing cache
tag and create a custom tag based on that code. But do not forget, django caching is quite strong and complex(like supporting different languages in template caching).
精彩评论