【发布时间】:2020-01-04 12:35:30
【问题描述】:
我是 Django 新手,我正在使用系统 Windows 10、Django 版本 3.0.1、python 3.6 我尝试使用为这个问题提供的所有相关解决方案,但不幸的是,这些解决方案都没有解决我的问题。 我在 myapp 和 "index.html" 里面创建了一个名为 templates 的文件夹,我在我的 views 中写了几行代码.py 文件为
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
def index(request):
template = loader.get_template('index.html')
return HttpResponse(template.render())
这是我的 settings.py
BASE_DIR = (os.path.dirname(os.path.abspath(__file__))
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'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',
],
},
},
]
**回溯错误**
Template loader postmortem
Django tried loading these templates, in this order:
Using engine django:
* django.template.loaders.filesystem.Loader: E:\djangoLearning\myproject\myapp\templates\index.html (Source does not exist)
* django.template.loaders.app_directories.Loader: E:\djangoLearning\djangoenv\lib\site-packages\django\contrib\admin\templates\index.html (Source does not exist)
* django.template.loaders.app_directories.Loader: E:\djangoLearning\djangoenv\lib\site-packages\django\contrib\auth\templates\index.html (Source does not exist)
* django.template.loaders.app_directories.Loader: E:\djangoLearning\myproject\myapp\templates\index.html (Source does not exist)
Traceback (most recent call last):
File "E:\djangoLearning\djangoenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "E:\djangoLearning\djangoenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "E:\djangoLearning\djangoenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\djangoLearning\myproject\myapp\views.py", line 9, in index
template = loader.get_template('index.html')
File "E:\djangoLearning\djangoenv\lib\site-packages\django\template\loader.py", line 19, in get_template
raise TemplateDoesNotExist(template_name, chain=chain)
Exception Type: TemplateDoesNotExist at /index/
Exception Value: index.html
工作目录
myproject
myapp
templates
index.html
【问题讨论】:
-
您说您在
myprojects目录下创建了模板,但在您的工作目录上它位于myapp下。但是如果在myapp下你可以试试template = loader.get_template('myapp/index.html')。 -
谢谢,我编辑了,其实templates目录只在myapp下
标签: django django-templates python-3.6