Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 repeat the html to be cached. Is there some clever way around this, other than putting it in an include? Thanks.

like image 817
asciitaxi Avatar asked Jan 31 '26 02:01

asciitaxi


1 Answers

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 %}
like image 102
Visa Kopu Avatar answered Feb 02 '26 14:02

Visa Kopu