(我的專案目錄稱為test,有問題的應用程式稱為posts)
Django 嘗試按以下順序加載這些模板:
使用引擎 Django:
django.template.loaders.app_directories.Loader: /path-to-app-dir/virtual/test/posts/templates/index.html (Source does not exist)
django.template.loaders.app_directories.Loader: /path-to-app-dir/virtual/platform/lib/python3.10/site-packages/django/contrib/admin/templates/index.html (Source does not exist)
django.template.loaders.app_directories.Loader: /path-to-app-dir/virtual/platform/lib/python3.10/site-packages/django/contrib/auth/templates/index.html (Source does not exist)
視圖.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return render(request,'templates/index.html')
網址.py
from django.urls import path
from . import views
urlpatterns=[
path('', views.index)
]
我已經在 Settings.py 中提到了該應用程式,因此這可能不是問題。
我究竟做錯了什么 ?
檔案樹
uj5u.com熱心網友回復:
模板放置在posts/templates/posts/. 如果您啟用APP_DIRS,則它將查找templates/所有應用程式中的所有目錄,但它仍位于一個posts/目錄下,因此您可以通過以下方式訪問模板:
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return render(request,'posts/index.html')
uj5u.com熱心網友回復:
您需要在settings.py.
設定.py
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [BASE_DIR / "templates"], # BASE_DIR / Your-templates-folder
"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",
],
},
},
]
既然你已經index.html在posts檔案夾下,模板路徑views.py應該是templates/posts/index.html
視圖.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return render(request, 'templates/posts/index.html')
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/396958.html
