django 片段缓存仅适用于匿名用户
我想为匿名用户使用 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。除了将其包含在其中之外,是否有一些聪明的方法可以解决此问题?谢谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试将经过身份验证的用户的缓存超时设置为零。
视图.py:
模板:
Try setting the cache timeout to zero for authenticated users.
views.py:
Template:
不确定我理解这个问题...
Not sure I understand the problem...
您可以通过将额外参数传递给
cache
标记来指定缓存,例如:检查 此处了解更多信息...
但这也将为登录用户缓存数据......
可能你必须编写一个自定义模板标签。您可以首先检查现有的
cache
标记,然后根据该代码创建自定义标记。但不要忘记,django 缓存非常强大且复杂(比如在模板缓存中支持不同的语言)。You can specify caching with passing extra parameters to
cache
tag like: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).