3

我想为匿名用户使用 django 片段缓存,但为经过身份验证的用户提供新鲜数据。这似乎工作正常:

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

唯一的问题是我必须重复要缓存的 html。除了把它放在一个包含中之外,还有什么聪明的方法可以解决这个问题吗?谢谢。

4

4 回答 4

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 %}
于 2011-12-12T08:52:27.973 回答
1
{% with cache_timeout=user.is_staff|yesno:"0,300" %}
    {% cache cache_timeout cacheidentifier user.is_staff %}
            your content here
    {% endcache %}
{% endwith %}
于 2014-07-01T20:42:47.230 回答
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).

于 2011-12-12T09:12:57.450 回答
0

不确定我是否理解问题...

{% 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 %}
于 2011-04-21T05:44:47.693 回答