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

Django收据系统渲染时遇TemplateDoesNotExist错误求助

收据管理系统TemplateDoesNotExist异常排查方案

问题概述

基于Django 5.2.1 + Python 3.12.3开发的收据管理系统,访问根路径时触发TemplateDoesNotExist异常,提示找不到base.html模板。已确认INSTALLED_APPS中添加了业务应用receiptsiclife,且模板文件已放置,但问题仍未解决。

错误详情

  • 请求方式:GET
  • 请求URL:http://127.0.0.1:8000/
  • 异常信息:Django尝试加载base.html的路径均不存在,包括/home/aessumen/receiptsystemsiclife/receiptsystemsiclife/templates/base.html及第三方库、应用内模板路径。错误触发点为/home/aessumen/receiptsystemsiclife/receiptsystemsiclife/receiptsiclife/templates/receiptsiclife/home.html第1行的{% extends 'base.html' %}语句,最终抛出Exception Type: TemplateDoesNotExist,Exception Value: base.html。

排查与修复步骤

1. 检查模板目录结构与引用路径

Django模板搜索遵循两种规则:

  • 全局模板:需放置在项目根目录的templates文件夹下(路径为/home/aessumen/receiptsystemsiclife/templates/base.html),此时{% extends 'base.html' %}引用有效。
  • 应用内模板:若将base.html放在业务应用内,需放置在receiptsiclife/templates/receiptsiclife/base.html,同时将home.html中的引用改为{% extends 'receiptsiclife/base.html' %}。

2. 完善settings.py中的TEMPLATES配置

当前提供的settings.py缺失关键的TEMPLATES配置项,需补充以确保Django能正确搜索模板路径:

# settings.py 补充内容
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],  # 配置项目根模板目录
        'APP_DIRS': True,  # 开启应用内模板自动搜索
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

3. 验证模板文件命名与权限

  • 确认base.html文件名拼写正确(Linux系统下大小写敏感,需严格匹配)。
  • 检查模板文件的读写权限,确保Django进程能访问该文件。

4. 确认INSTALLED_APPS配置

确保receiptsiclife已添加至INSTALLED_APPS列表,且位置无冲突(若存在同名模板,应用顺序会影响搜索优先级,建议将业务应用放在第三方应用之后)。

代码修正示例

若采用应用内模板方案,修改home.html的extends语句:

<!-- receiptsiclife/templates/receiptsiclife/home.html -->
{% extends 'receiptsiclife/base.html' %}
<!-- 其余内容保持不变 -->

内容的提问来源于stack exchange,提问作者Fiifi Essumen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 23:24:49