我尝试使用render来显示在PyCharm上编辑的HTML,但是当我输入地址:时127.0.0.1:8000/index/,TemplateDoesNotExist出现以下异常:
TemplateDoesNotExist at/index/index.html请求方法:GET请求URL:http://127.0.0.1 :8000/index/ Django版本:1.11.1异常类型:TemplateDoesNotExist异常值:index.html异常位置:D:\ python3 get_template中的.6.1\lib\site-packages\django\template\loader.py,第25行Python可执行文件:D:\ python3.6.1\python.exe Python版本:3.6.1 Python路径:
['C:\ Users\Administrator\guest','D:\ python3.6.1\python36.zip','D:\ python3.6.1\DLLs','D:\ python3.6.1\lib','D:\ python3.6.1',' D:\ python3.6.1\lib\site-packages']服务器时间:星期五,2017年6月2日03:30:58 + 0000`TemplateDoesNotExist at/index /
settings.py:
ROOT_URLCONF = 'guest.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'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',
],
},
},
]
Run Code Online (Sandbox Code Playgroud)
views.py:
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,"index.html")
Run Code Online (Sandbox Code Playgroud)
PyCharm的屏幕截图:

我已经尝试了StackOverflow上提供的一些方法,但它们不起作用.这个例外是由错误的dirs引起的吗?我该如何处理这种情况?
看这个:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'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',
],
},
},
]
Run Code Online (Sandbox Code Playgroud)
特别
'DIRS': [],
Run Code Online (Sandbox Code Playgroud)
你需要告诉Django在哪里寻找你的模板.如果主项目根目录中有模板文件夹.然后加
os.path.join(BASE_DIR, 'templates')
Run Code Online (Sandbox Code Playgroud)
这假设您的项目具有以下结构:
root
app1
...
templates/
what we're referencing with os.path.join(BASE_DIR, "templates")
....
static/
what we're referencing with STATIC_ROOT = os.path.join(BASE_DIR, "static")
...
Run Code Online (Sandbox Code Playgroud)
如果您要在应用程序中放置模板.有两件事.
您项目中的应用程序将需要此模板文件夹的结构
app name (folder)
templates (folder)
app name (folder)
(template files) e.g. - "base.html"
Run Code Online (Sandbox Code Playgroud)
您需要添加此行
os.path.join(BASE_DIR, APP NAME, "templates")
Run Code Online (Sandbox Code Playgroud)
附录:毫无疑问,你也会遇到这个问题......所以让我们继续讨论它.
如果要扩展/包含应用程序中的模板(不在基本模板文件夹中),则需要引用它们所在的位置:
示例:我在"myapp/templates/myapp/template.html"中有一个模板,我想要包含它.
然后,我会做{% include "myapp/template.html" %}或者扩展{% extend "myapp/template.html" %}.如果它们位于基本模板文件夹中,那么您可以直接引用它们"template.html"
| 归档时间: |
|
| 查看次数: |
4587 次 |
| 最近记录: |