我的 Django 结构是:
testing
contacts
__init__.py
templates
contacts
index.html
(additional modules)
testing
__init__.py
templates
testing
test.html
urls.py
(additional modules)
在主要 URL 模块 testing.urls
中,我有一个 urlconf 如下:
url(r'^testing/$', TemplateView.as_view(template_name='testing/test.html'))
问题是,它一直在 contacts.templates.contacts
中查找 test.html
文件。使用现有的 urlcon,调试页面显示如下:
模板加载器事后分析
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
Using loader django.template.loaders.app_directories.Loader:
/Library/Python/2.7/site-packages/django/contrib/admin/templates/testing/test.html (File does not exist)
/Library/Python/2.7/site-packages/django/contrib/auth/templates/testing/test.html (File does not exist)
/Users/*/Developer/django/testing/contacts/templates/testing/test.html (File does not exist)
它总是默认......................................^^^^^^^^^^ 联系人
文件夹出于某种原因。 TemplateView 或 template_name
是否有其他一些参数可以控制它?任何帮助表示赞赏!
更新 - 在 settings.py
中
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
最佳答案
testing/testing
目录当前未被 Django 搜索。最简单的修复方法是将它添加到 DIRS
设置中:
'DIRS': [os.path.join(BASE_DIR, 'testing', 'templates')],
另一种选择是将 testing
添加到您的 INSTALLED_APPS
设置中。然后 Django 会找到您的模板,因为您有 APP_DIRS=True
。但是我不推荐这样做,因为在您的情况下 testing/testing
是包含 settings.py
和根 url 配置的特殊目录。
关于python - Django TemplateView 在错误的地方搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34570229/