3

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.

asciitaxi
  • 1,369
  • 1
  • 16
  • 16

4 Answers4

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 %}
Visa Kopu
  • 695
  • 3
  • 7
  • 20
  • This is [a similar answer](http://stackoverflow.com/a/24519003/64911) that puts all the logic in the template instead (for better or worse). – mlissner Dec 11 '15 at 22:34
1
{% with cache_timeout=user.is_staff|yesno:"0,300" %}
    {% cache cache_timeout cacheidentifier user.is_staff %}
            your content here
    {% endcache %}
{% endwith %}
panosmm
  • 183
  • 1
  • 8
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 %}
John Mee
  • 50,179
  • 34
  • 152
  • 186
  • It's the same stuff for both anonymous and authenticated users. The only difference is that one is inside the cache tags and one is outside. – asciitaxi Apr 21 '11 at 06:24
  • Although this is a valid approach, it might break in a different situation: e.g. having a `{% block something %}{% endblock %}` will raise an error (same blocktag used more than once is not allowed) – Hussam Jan 04 '13 at 12:12
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
  • 18,172
  • 15
  • 83
  • 114