【发布时间】:2020-06-27 04:22:58
【问题描述】:
我正在按照 Building Django 2.0 Web Applications 一书学习 django,到目前为止一切正常。该项目称为配置,并且有一个称为核心的应用程序。应用程序(核心)有它自己的模板目录(config/core/templates)和它自己的 urls.py 文件(config/core/urls.py),它由根 urls.py 文件(config/config/urls.py)加载。 py)。当我运行服务器并访问其中一个核心 URL 时会发生什么:
TemplateDoesNotExist 在 /movies
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.filesystem.Loader: /home/sugarcane/projects/config/templates/core/movie_list.html (Source does not exist)
django.template.loaders.app_directories.Loader: /home/sugarcane/projects/config/core/templates/core/movie_list.html (Source does not exist)
django.template.loaders.app_directories.Loader: /home/sugarcane/projects/config/venv/lib/python3.8/site-packages/django/contrib/admin/templates/core/movie_list.html (Source does not exist)
django.template.loaders.app_directories.Loader: /home/sugarcane/projects/config/venv/lib/python3.8/site-packages/django/contrib/auth/templates/core/movie_list.html (Source does not exist)
它正在寻找的模板文件实际上是: /home/sugarcane/projects/config/core/templates/movie_list.html
为什么它在错误的目录中查找?
这里是 urls.py 文件:
config/core/urls.py:
from django.urls import path
from . import views
app_name = 'core'
urlpatterns = [
path('movies', views.MovieList.as_view(), name='MovieList'),
]
和
config/config/urls.py
from django.contrib import admin
from django.urls import path, include
import core.urls
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(core.urls, namespace='core')),
]
在 settings.py 中,我得到了这个:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates')
]
,
'APP_DIRS': True,
'OPTIONS': {
...
},
},
]
我读到 'APP_DIRS': True 告诉 django 在每个应用程序目录中查找模板目录。我的问题是它正在寻找不存在的模板/核心。为什么要搜索core子目录?
一个明显的解决方案是将movie_list.html模板文件放入config/core/templates/core,我只是想知道为什么书上告诉我直接把它放入config/core/templates。也许这是因为这本书是为 Django 2.0 编写的,而我使用的是 Django 3.0?
【问题讨论】:
-
在网址
urlpatterns = [ path('movies/', views.MovieList.as_view(), name='MovieList'), ]的电影末尾添加斜线