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

Django报错TemplateDoesNotExist:无法找到customer/index.html模板

Django TemplateDoesNotExist 错误解决方案

问题描述

运行Django项目时触发TemplateDoesNotExist错误,报错信息:

TemplateDoesNotExist at / customer/index.html

提供的urls.py配置代码:

from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static 
from customer.views import Index, About

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', Index.as_view(), name='index'),
    path('about/', About.as_view(), name='about'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

解决步骤

1. 核对模板文件路径

Django默认会在每个app的templates目录下查找模板,需确保:

  • 在customer app目录下创建嵌套结构:templates/customer
  • 将index.html放在customer/templates/customer/路径下,完整路径为项目根目录/customer/templates/customer/index.html

2. 确认APP已注册到项目

打开项目根目录的settings.py,检查INSTALLED_APPS列表是否包含'customer':

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'customer',  # 必须存在这一行
]

3. 检查视图类的模板配置

如果Index是基于TemplateView的类视图,确认template_name参数路径正确:

# customer/views.py
from django.views.generic import TemplateView

class Index(TemplateView):
    template_name = 'customer/index.html'  # 路径需与实际文件位置匹配

4. 清理缓存并重启服务

缓存可能导致模板查找异常,执行以下操作:

  • 停止当前Django开发服务器
  • 删除所有app目录下的__pycache__文件夹
  • 重新启动服务器:python manage.py runserver

5. 验证TEMPLATES全局配置(可选)

若使用了自定义全局模板目录,确认settings.py中的TEMPLATES配置正确:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],  # 全局模板目录路径需正确
        'APP_DIRS': True,  # 必须设为True,Django才会自动查找app内的templates目录
        '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',
            ],
        },
    },
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 16:51:13