我是 Django 框架的初学者。我创建了我的项目,创建了我的应用程序并测试它,它工作正常,直到我决定添加模板。我不知道错误来自哪里,因为我遵循 Django 文档的说明,在应用程序文件夹中创建文件夹名称模板,使用应用程序名称创建一个文件夹,最后在该文件夹中创建 HTML 文件。
注意:除了模板之外,其他路由都工作正常
请查看下面我的文件结构和错误的屏幕截图。

错误
TemplateDoesNotExist at /blog/
Blog/index
Request Method: GET
Request URL: http://127.0.0.1:8000/blog/
Django Version: 4.0.1
Exception Type: TemplateDoesNotExist
Exception Value:
Blog/index
Exception Location: C:\Python39\lib\site-packages\django\template\loader.py, line 19, in get_template
Python Executable: C:\Python39\python.exe
Python Version: 3.9.4
Python Path:
['C:\\Users\\Maxwell\\Desktop\\Django\\WebApp',
'C:\\Python39\\python39.zip',
'C:\\Python39\\DLLs',
'C:\\Python39\\lib',
'C:\\Python39',
'C:\\Users\\Maxwell\\AppData\\Roaming\\Python\\Python39\\site-packages',
'C:\\Python39\\lib\\site-packages',
'C:\\Python39\\lib\\site-packages\\win32',
'C:\\Python39\\lib\\site-packages\\win32\\lib',
'C:\\Python39\\lib\\site-packages\\Pythonwin']
Server time: Sun, 23 Jan 2022 12:04:18 +0000
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.app_directories.Loader: C:\Users\Maxwell\Desktop\Django\WebApp\Blog\templates\ Blog\index (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Python39\lib\site-packages\django\contrib\admin\templates\ Blog\index (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Python39\lib\site-packages\django\contrib\auth\templates\ Blog\index (Source does not exist)
Run Code Online (Sandbox Code Playgroud)
应用程序/views.py
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def index(request,name):
return HttpResponse(f'Hello {name}')
def html(request):
return render(request,' Blog/index.html')
Run Code Online (Sandbox Code Playgroud)
小智 11
我也遇到了这种情况,并浏览了这里讨论路径的大部分答案,并编辑了 settings.py 中的“模板”功能。最后,这是因为我忘记将我的应用程序添加到settings.py文件中的已安装应用程序部分。我在https://docs.djangoproject.com/en/4.0/intro/tutorial03/#write-views-that-actually-do-something的文档中看到了这一点
小智 5
如果@Willem van Onsem 的答案不起作用
在主目录“与 WebApp 处于同一级别”中创建一个 templates 文件夹,然后在其中为每个应用程序创建文件夹
在你的settings.py中你会发现TEMPLATES选项
TEMPLATES = [
{
...
'DIRS': [os.path.join(BASE_DIR,'templates')],#add this line
...
]
Run Code Online (Sandbox Code Playgroud)
当你想使用模板时
return render(request,"template_folder/template_name.html")
Run Code Online (Sandbox Code Playgroud)
似乎您使用 渲染模板Blog/index,但您需要指定整个文件名,因此Blog/index.html并且没有前导(或尾随)空格:
def html(request):
return render(request, 'Blog/index.html')Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19891 次 |
| 最近记录: |