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

Django提示已存在模板不存在:{% include %}路径问题排查

Django跨目录模板引用问题解决方法

核心问题分析

你犯了两个关键错误:

  1. 模板文件不应放在static目录下——static是用来存放CSS、JS、图片等静态资源的,Django的模板加载机制虽然可以通过配置读取其他目录,但这不符合框架规范,也容易引发混淆。
  2. {% include %}中使用了文件系统相对路径——Django模板标签里的路径是相对于模板加载目录的,不是本地文件系统的相对路径,../static/...这种写法完全不被模板引擎识别。

规范解决步骤(推荐)

  1. 调整目录结构
    把static/libraries/templates/our-tech-stack.html移动到根目录的templates文件夹下,比如改成templates/libraries/our-tech-stack.html,最终结构:

    Root/
    ├── static/
    ├── templates/
    │   ├── calling-template.html
    │   └── libraries/
    │       └── our-tech-stack.html
    
  2. 修改模板引用
    在calling-template.html里直接用模板加载路径引用:

    {% include "libraries/our-tech-stack.html" %}
    
  3. 确认settings配置
    确保settings.py里的TEMPLATES配置中,DIRS包含根templates目录:

    TEMPLATES = [
        {
            # ...其他配置
            'DIRS': [os.path.join(BASE_DIR, 'templates')],
            'APP_DIRS': True,
            # ...其他配置
        },
    ]
    

    这样Django会自动从templates目录下查找子文件夹里的模板。

不规范但临时解决(不推荐)

如果一定要保留模板在static/libraries/templates目录下:

  1. 保留settings配置
    确保TEMPLATES的DIRS已经配置了该路径:

    'DIRS': [
        os.path.join(BASE_DIR, 'templates'),
        os.path.join(BASE_DIR, 'static/libraries/templates'),
    ],
    
  2. 修改模板引用
    直接写模板文件名(因为Django会遍历DIRS里的所有目录查找),不需要相对路径:

    {% include "our-tech-stack.html" %}
    

内容的提问来源于stack exchange,提问作者James Sinclair

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 09:35:03