[Django]-Django fragment caching for anonymous users only

2👍

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 %}

1👍

{% with cache_timeout=user.is_staff|yesno:"0,300" %}
    {% cache cache_timeout cacheidentifier user.is_staff %}
            your content here
    {% endcache %}
{% endwith %}

0👍

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 %}

0👍

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).

👤Mp0int

Leave a comment