2

我的 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)

contacts出于某种原因,它始终默认为.......................^^^^^^^^^^文件夹。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',
            ],
        },
    },
]
4

2 回答 2

4

testing/testingDjango 当前没有搜索该目录。最简单的解决方法是将其添加到DIRS设置中:

'DIRS': [os.path.join(BASE_DIR, 'testing', 'templates')],

另一种选择是添加testing到您的INSTALLED_APPS设置中。然后 Django 会找到你的模板,因为你有APP_DIRS=True. 但是我不建议这样做,因为在您的情况下testing/testing是包含settings.py和根 url 配置的特殊目录。

于 2016-01-02T20:41:46.640 回答
3

通过指定"APP_DIRS": True,您是在告诉 django 在安装的每个应用程序中搜索模板文件。检查您的settings.py所有应用程序是否都包含在INSTALLED_APPS. 如果是,您可以尝试强制 django 在您的应用程序中查找模板。

TEMPLATES = [
    {
        'DIRS': [os.path.join(BASE_DIR,  'testing', 'templates')],
        ....
    },
]
于 2016-01-02T20:42:51.227 回答