简单的 hello world 项目中 django 中的 TemplateDoesNotExist 错误

mit*_*ell 0 python django django-templates

我在 django 中使用模板时遇到问题。我相信我的模板位于正确的位置,并且在查看错误日志中的路径后,该文件就在那里。我也让它在不使用的情况下工作render()。但我已经尝试了多种方法,并且在错误日志中它显示了一个路径,我可以按照该路径到达我尝试渲染的 html 文件。

这是我的项目的文件结构(注意:该文件结构实际上位于 C:\my_website 内部)

在此输入图像描述

相关代码:
下面是我创建的 hello 应用程序的视图。目前的情况是有错误,但如果我注释掉调用并使用未注释的代码,它会显示index.html C:\my_website\my_website\hello\viewsrender()的内容

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

# Create your views here.
import os
import logging #MS ADDED
logger = logging.getLogger(__name__)#MS ADDED


def index(request):
    #!!! It works with this stuff uncommented
    #index_path =  os.path.join(os.path.dirname(os.path.dirname(__file__)),'hello\\templates\\hello\\index.html')
    #logger.error('Views - index_path is ' + index_path) # MS ADDED
    #with open(index_path) as f:
    #   html_string = f.read()
    #return HttpResponse(html_string)
    return render(request, 'hello/index.hmtl')

Run Code Online (Sandbox Code Playgroud)

以下是我在设置中更改的所有内容。我在 Django 文档中读到,如果您没有指定路径,它将在您创建的应用程序的模板目录中查找(你好)。但是在 TEMPLATES 中将 DIRS 留空确实会产生 TemplateDoesNotExist 异常。所以我尝试了一些其他不起作用的方法,如下所示。
C:\我的网站\我的网站\我的网站\设置


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'hello.apps.HelloConfig',
]

SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))#MS ADDED
Temp_Path = os.path.realpath('.')# MS ADDED
index_path =  os.path.join(os.path.dirname(os.path.dirname(__file__)),'hello/templates')#MS ADDED


#MS Note: I tried for DIRS below os.path.join(SETTINGS_PATH,'templates')
#MS Note: I tried for DIRS below Temp_Path + "hello/templates"
#MS Note: I tried for DIRS Below  os.path.join(os.path.dirname(os.path.dirname(__file__)),'hello/templates')

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [index_path],
        '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',
            ],
        },
    },
]
Run Code Online (Sandbox Code Playgroud)

以下是网址
C:\my_website\my_website\my_website

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

from hello import views

urlpatterns = [
    path('',views.index,name='index'),
    path('admin/', admin.site.urls),
    #path('hello/', hello.views.index),
]
Run Code Online (Sandbox Code Playgroud)

错误日志:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/

Django Version: 3.1.2
Python Version: 3.8.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'hello.apps.HelloConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Template loader postmortem
Django tried loading these templates, in this order:

Using engine django:
    * django.template.loaders.filesystem.Loader: C:\my_website\my_website\templates\hello\index.hmtl (Source does not exist)
    * django.template.loaders.app_directories.Loader: C:\my_website\env\lib\site-packages\django\contrib\admin\templates\hello\index.hmtl (Source does not exist)
    * django.template.loaders.app_directories.Loader: C:\my_website\env\lib\site-packages\django\contrib\auth\templates\hello\index.hmtl (Source does not exist)
    * django.template.loaders.app_directories.Loader: C:\my_website\my_website\hello\templates\hello\index.hmtl (Source does not exist)



Traceback (most recent call last):
  File "C:\my_website\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\my_website\env\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\my_website\my_website\hello\views.py", line 16, in index
    return render(request, 'hello/index.hmtl')
  File "C:\my_website\env\lib\site-packages\django\shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\my_website\env\lib\site-packages\django\template\loader.py", line 61, in render_to_string
    template = get_template(template_name, using=using)
  File "C:\my_website\env\lib\site-packages\django\template\loader.py", line 19, in get_template
    raise TemplateDoesNotExist(template_name, chain=chain)

Exception Type: TemplateDoesNotExist at /
Exception Value: hello/index.hmtl

Run Code Online (Sandbox Code Playgroud)

在错误日志中它说这个
C:\my_website\my_website\hello\templates\hello\index.hmtl (Source does not exist) 但它确实存在并且只包含 <h1>Hello World! aafa</h1>

使用视图中注释掉的代码,应用程序将显示:

在此输入图像描述

我正在使用 django 版本 3.1.2 和 python 版本 3.8.6
任何帮助将不胜感激

小智 5

在渲染函数中,您传递“index.hmtl”而不是“index.html”