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

Django 3.2版本如何在views.py中动态修改TEMPLATES的DIRS路径

Django 3.2.x 动态按设备类型切换模板路径解决方案

⚠️ 注意:绝对不要在视图中直接修改settings.TEMPLATES[0]['DIRS'],Django的settings是全局单例,多请求并发场景下会出现线程安全问题,导致不同用户拿到错误的模板路径。推荐以下几种安全可行的实现方案:

方案1:渲染时拼接模板路径前缀(最简便无侵入)

不需要修改任何全局配置,保持默认TEMPLATES.DIRS = ['templates']即可,渲染模板时直接在路径前拼接设备前缀:

from django.shortcuts import render

def your_view(request):
    # 你已实现的设备判断逻辑,已经给request.template_prefix赋值desktop/mobile
    # 模板实际存放路径为 templates/desktop/xxx.html 或 templates/mobile/xxx.html
    template_path = f"{request.template_prefix}/index.html"
    return render(request, template_path, context={"your_key": "your_value"})

方案2:调用render时动态传入dirs参数(自定义模板查找根路径)

如果你需要完全替换模板的查找根路径,不需要手动拼接模板路径前缀,可以直接给render方法传入dirs参数覆盖默认配置:

from django.shortcuts import render

def your_view(request):
    # 动态生成当前请求对应的模板根路径
    custom_template_dirs = [f"templates/{request.template_prefix}"]
    # 直接写模板文件名即可,Django会优先从custom_template_dirs下查找
    return render(request, "index.html", context={"your_key": "your_value"}, dirs=custom_template_dirs)

方案3:全局统一封装,无需每个视图重复写逻辑

如果项目全量需要这套设备匹配模板的逻辑,可以通过封装父类、装饰器等方式统一处理,避免重复代码:

类视图实现:重写get_template_names方法

from django.views.generic import TemplateView

# 先定义通用的设备适配基类视图
class DeviceAdaptTemplateView(TemplateView):
    def get_template_names(self):
        prefix = self.request.template_prefix
        return [f"{prefix}/{tpl_name}" for tpl_name in super().get_template_names()]

# 业务视图直接继承基类即可,不需要额外写适配逻辑
class HomeView(DeviceAdaptTemplateView):
    template_name = "index.html"

函数视图实现:使用装饰器统一处理

from django.template.response import TemplateResponse

# 定义通用装饰器
def auto_match_device_template(view_func):
    def wrapper(request, *args, **kwargs):
        resp = view_func(request, *args, **kwargs)
        # 仅处理TemplateResponse类型的响应
        if isinstance(resp, TemplateResponse):
            resp.template_dirs = [f"templates/{request.template_prefix}"]
        return resp
    return wrapper

# 业务视图加装饰器即可
@auto_match_device_template
def home_view(request):
    return TemplateResponse(request, "index.html", context={"your_key": "your_value"})

内容的提问来源于stack exchange,提问作者Kheersagar patel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 19:06:01