python - Django TemplateView 在错误的地方搜索

标签 python django django-urls urlconf

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

相关文章:

python - Django 共享库/类

python - 如何在 Django 模型中存储字符串数组?

python - 表单验证和 MultiValueDictKeyError

python - 如何避免从 Bash 脚本多次调用 Python 解释器?

python - 从 flask 蓝图中导入应用程序设置

python - TypeError at/__init__() 恰好接受 1 个参数(给定 2 个)

python - 如何在基于类的 View 中编写自己的方法并调用 url 中的方法

django - 如何在单个站点中的不同 django 应用程序之间进行交互?

python - 没有名为 backends.default.urls 的模块

Python - 在单独的子进程或线程中运行 Autobahn|Python asyncio websocket 服务器