使用 Django 模板新建HelloWorld 項目,瀏覽器輸入http://127.0.0.1:8000/ ,頁面輸出 Hello World!
報以下錯誤
TemplateDoesNotExist at /
hello.html
Request Method: | GET |
---|---|
Request URL: | http://127.0.0.1:8000/ |
Django Version: | 2.2.5 |
Exception Type: | TemplateDoesNotExist |
Exception Value: |
|
Exception Location: | D:\Program Files\Python\Python37\lib\site-packages\django-2.2.5-py3.7.egg\django\template\loader.py in get_template, line 19 |
Python Executable: | D:\Program Files\Python\Python37\python.exe |
Python Version: | 3.7.1 |
Python Path: |
|
Server time: | Mon, 16 Sep 2019 07:20:40 +0000 |
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django
:
django.template.loaders.filesystem.Loader
: F:\Python\HelloWorld\hello.html (Source does not exist)django.template.loaders.filesystem.Loader
: F:\Python\HelloWorld\templates\hello.html (Source does not exist)django.template.loaders.app_directories.Loader
: D:\Program Files\Python\Python37\lib\site-packages\django-2.2.5-py3.7.egg\django\contrib\admin\templates\hello.html (Source does not exist)django.template.loaders.app_directories.Loader
: D:\Program Files\Python\Python37\lib\site-packages\django-2.2.5-py3.7.egg\django\contrib\auth\templates\hello.html (Source does not exist)
解決方法:
根據查找資料 應修改 HelloWorld/settings.py 文件中 TEMPLATES 值(修改'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',
],
},
},
]
以下幾種方式都可以:
設置絕對路徑:
'DIRS': ['F:\\Python\\HelloWorld\\HelloWorld\\templates',],
或
'DIRS': [BASE_DIR, "templates",
os.path.join('F:\\Python\\HelloWorld\\HelloWorld','templates'),],
相對路徑:
'DIRS': [os.path.join(BASE_DIR,'HelloWorld/templates')],
或
'DIRS': [BASE_DIR, "templates",
os.path.join(BASE_DIR,'HelloWorld/templates'),],
https://stackoverflow.com/questions/1926049/django-templatedoesnotexist