首页 > 解决方案 > TemplateDoesNotExist at / 模板路径

问题描述

我想创建投资组合的后端,我正在尝试使用模板,但它说它不存在,但在错误消息中显示了正确的文件路径。这是 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': [
            ....
        ],
    },
  },


]

目录结构为:

1. 我的项目 - 我的项目 -init.py -settings.py -urls.py -manage.py -my app 2. 模板 3. 静态

核心是应用名称

标签: pythondjangotemplates

解决方案


试试这个

将主视图更改为

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

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

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

推荐阅读