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

Django中如何添加模板目录?解决TemplateDoesNotExist错误

Django模板找不到错误排查

问题现象

访问/task/路径时触发TemplateDoesNotExist at /task/错误。

项目文件夹结构

项目文件夹结构

关键代码片段

taskmate/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('task/',include('todolist_app.urls')),
    path('todolist/',include('todolist_app.urls')),
]

todolist_app/urls.py

from django.urls import path
#from todolist_app import views
from . import views

urlpatterns = [
    path('', views.todolist, name='todolist'),
]

todolist_app/views.py

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def todolist(request):
    return render(request, 'todolist.html',{})

settings.py 模板配置

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [(os.path.join(os.path.dirname(os.path.dirname(__file__)),'todolist_app/templates').replace('\\','/'))],#'DIRS': 
        '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',
            ],
        },
    },
]

已尝试的无效配置

怀疑问题出在模板DIRS配置上,试过以下几种写法均无效:

'DIRS': [os.path.join(BASE_DIR,'templates')],
'DIRS': [os.path.join(os.path.dirname(__file__),'templates').replace('\\','/')],#'DIRS': 
'DIRS': [(os.path.join(os.path.dirname(os.path.dirname(__file__)),'todolist_app/templates').replace('\\','/'))],#'DIRS': 

备注:已将todolist_app添加到INSTALLED_APPS中。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:05:25