【问题标题】:Django TemplateView searching in wrong placeDjango TemplateView在错误的地方搜索
【发布时间】:2016-04-06 19:56:16
【问题描述】:

我的 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',
            ],
        },
    },
]

【问题讨论】:

  • 如何在settings.py中定义模板目录?
  • @Mirac7 更新了settings.py部分的问题

标签: python django django-urls urlconf


【解决方案1】:

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

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

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

【讨论】:

  • 感谢您的回答,以及反对将testing 应用程序放入INSTALLED_APPS 的额外建议。您建议将“根”(testing) 应用程序放在外面,因为它只能用作正确应用程序的一种路由器?
  • 包含settings.py 和root url conf 的目录通常不包含在INSTALLED_APPS 中。正如您所说,根 url conf 通常包含来自其他应用程序的 url。我之前看到有人将它包含在INSTALLED_APPS 中,所以我并不是说你绝对不应该这样做。
【解决方案2】:

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

TEMPLATES = [
    {
        'DIRS': [os.path.join(BASE_DIR,  'testing', 'templates')],
        ....
    },
]

【讨论】:

    猜你喜欢
    • 2014-05-21
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 2011-12-29
    • 2014-07-07
    相关资源
    最近更新 更多