You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django模板中显示本地内存缓存?

在Django模板中显示本地内存缓存的可行方法
  • 方法一:在视图中获取缓存并传入模板上下文
    直接在视图函数里调用cache.get()取出缓存内容,再通过render函数的上下文参数传递给模板,模板中直接用变量名渲染即可。

    视图代码(views.py):

    from django.core.cache import cache
    from django.shortcuts import render
    
    def index(request):
        # 第二个参数为默认值,避免缓存不存在时返回None
        message = cache.get("message", "")
        return render(request, "index.html", {"message": message})
    

    模板代码(index.html):

    {{ message }}
    
  • 方法二:自定义模板标签
    要是需要在多个模板里频繁获取缓存内容,可以自定义一个简单的模板标签,实现模板内直接调用获取指定缓存键的功能。

    实现步骤:

    1. 在你的Django应用下创建templatetags目录(必须包含__init__.py空文件),新建cache_tags.py文件:
    from django import template
    from django.core.cache import cache
    
    register = template.Library()
    
    @register.simple_tag
    def get_cache(key, default=""):
        return cache.get(key, default)
    
    1. 在模板中加载自定义标签并使用:
    {% load cache_tags %}
    
    {% get_cache "message" %}
    

内容的提问来源于stack exchange,提问作者Super Kai - Kazuya Ito

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 16:36:06