我是遵循這個 Django 教程(https://www.w3schools.com/django/django_templates.php)的初學者,在制作 html 模板并修改 views.py 檔案(名稱已洗掉隱私):
Internal Server Error: /members
Traceback (most recent call last):
File "C:\Users\\myproject\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\\myproject\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\\myproject\myworld\members\views.py", line 5, in index
template = loader.get_template('myfirst.html')
File "C:\Users\\myproject\lib\site-packages\django\template\loader.py", line 19, in get_template
raise TemplateDoesNotExist(template_name, chain=chain)
django.template.exceptions.TemplateDoesNotExist: myfirst.html
[26/Oct/2022 16:51:01] "GET /members HTTP/1.1" 500 64964
試過這個:
from django.http import HttpResponse
from django.shortcuts import loader
def index(request):
template = loader.get_template('myfirst.html')
return HttpResponse(template.render())
期待這個:
<!DOCTYPE html>
<html>
<body><h1>Hello World!</h1>
<p>Welcome to my first Django project!</p>
</body>
</html>
uj5u.com熱心網友回復:
首先,您必須創建一個模板檔案夾,然后在其中創建您的 HTML 檔案“myfirst.html”,然后在其中創建您的 HTML 標簽,例如:
<h1>Hello, World</h1>
uj5u.com熱心網友回復:
創建一個您.html將居住的目錄:
templates在目錄中創建一個目錄app(即app/templates/app/template_name.html:)- 或者,在目錄中創建一個
templates檔案夾project(即:templates/template_name.html或templates/app/template_name.html),如果您選擇使用此選項,則必須django通過更新TEMPLATES設定來指向此目錄
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
# Add path to templates
"DIRS": [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",
],
},
},
]
- 然后,在您的視圖中,指定
.html檔案的路徑
例子:
- 使用選項 1:路徑將是
app/template_name.html - 使用選項 2:路徑將是
template_name.html或app/template_name.html(取決于您的檔案夾結構)
uj5u.com熱心網友回復:
為了更好地確定您的模板未呈現的原因,您應該利用DEBUG=True嘗試settings.py
通過瀏覽器訪問您的頁面應該顯示 Django 嘗試過的路徑,然后您將立即看到您的路徑未正確識別。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/521190.html
上一篇:Flask-SQLAlchemy引發TypeError:Query.paginate()接受1個位置引數,但給出了4個
下一篇:Django相關模型中的pk參考
