所以,我正在用 python 开发这个应用程序,当我尝试在浏览器中显示一些 html 时,我收到此错误:
TemplateDoesNotExist at /xPharma/hello/
hello.html
Request Method: GET
Request URL: http://127.0.0.1:8000/xPharma/hello/
Django Version: 4.2.11
Exception Type: TemplateDoesNotExist
Exception Value:
hello.html
Exception Location: C:\Users\Marco\.virtualenvs\XpharmBackend-9gJJ8jLG\lib\site-packages\django\template\loader.py, line 19, in get_template
Raised during: xPharma.views.say_hello
Python Executable: C: \Users\Marco\.virtualenvs\XpharmBackend-9gJJ8jLG\Scripts\python.exe
Python Version: 3.9.7
Python Path:
['C:\\Users\\Marco\\Desktop\\Desktop\\progetto X pharme\\XpharmBackend',
'C:\\Python39\\python39.zip',
'C:\\Python39\\DLLs',
'C:\\Python39\\lib',
'C:\\Python39',
'C:\\Users\\Marco\\.virtualenvs\\XpharmBackend-9gJJ8jLG',
'C:\\Users\\Marco\\.virtualenvs\\XpharmBackend-9gJJ8jLG\\lib\\site-packages']
Server time: Mon, 01 Apr 2024 15:44:22 +0000
但我发现我收到此错误,因为 python 正在错误的目录中搜索文件...
Using engine django:
django.template.loaders.app_directories.Loader: C:\Users\Marco\.virtualenvs\XpharmBackend-9gJJ8jLG\lib\site-packages\django\contrib\admin\templates\hello.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\Marco\.virtualenvs\XpharmBackend-9gJJ8jLG\lib\site-packages\django\contrib\auth\templates\hello.html (Source does not exist)
有没有办法更改此目录并将 python 重定向到我保存文件的位置?
编辑:根据要求,这是我的views.py(xPharma.views.say_hello):
from django.shortcuts import render
from django.http import HttpResponse
def say_hello(request):
return render(request,'hello.html')
问题:-
您的模板位置不正确。
答案:-
在 hello app 中创建一个名为
templates
的文件夹,然后将 hello.html
移入该文件夹。
保持views.py 中模板的路径不变。
这就是 django 的工作原理。
它会在您的
app_name/templates
文件夹中查找模板。