【问题标题】:TemplateDoesNotExist at / template pathTemplateDoesNotExist at / 模板路径
【发布时间】:2026-02-04 13:15:01
【问题描述】:

我想创建投资组合的后端,我正在尝试使用模板,但它说它不存在,但在错误消息中显示了正确的文件路径。 这是 urls.py:

from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls')),
]


if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL,
                         document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL,
                         document_root=settings.MEDIA_ROOT)

这是我的views.py:

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

def home(request):
    template = loader.get_template('home.html')
    return HttpResponse(template.render(request))

这是我的模板设置:

TEMPLATES = [
  {
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS':  [os.path.join(BASE_DIR, 'templates')],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            ....
        ],
    },
  },


]

目录结构为:

Core 是应用名称

【问题讨论】:

  • 请包括urls.py 以及完整的回溯。
  • @Ram 我已经做到了
  • 将 DIRS 更改为 [] 并尝试
  • @Sumithran 它返回相同的错误
  • 能否分享一下完整的错误回溯

标签: python django templates


【解决方案1】:

试试这个

将主视图更改为

def home(request):
    return render("home.html")

并在 settings.py 中将 DIRS 设置为空白

TEMPLATES = [
  {
    ...
    'DIRS':  [],
    ...
  }
]

【讨论】:

  • 我这样做了,错误改为:AttributeError at / 'str' object has no attribute 'get'
  • 您使用的是哪个版本的 Django?另外,分享您的完整 settings.py 文件。
  • 这是设置文件的链接[link] (github.com/Zeesky-code/Interactive-Resume-HNGi8/blob/main/…) 我使用的是 Django 3.2.6
【解决方案2】:

我建议你在你的 settings.py 中试试这个

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR = BASE_DIR / 'templates'
 
    TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATES_DIR,],
        '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',
            ],
        },
    },
]

然后在你的views.py中请求你的html

def home(request):
    return render(request, 'home.html')

在你的 urls.py 中

path('',views.home, name='home')

这种更好、更简洁的方式告诉 django 在哪里查找 fot 模板并告诉我您是否仍然遇到错误

【讨论】:

  • @ZainabLawal 添加回溯
【解决方案3】:

我通过将静态和模板目录移动到应用程序目录来修复它。

【讨论】: