懒惰的django.template.loaders.filesystem.Loader

时间:2015-11-03 10:40:56

标签: django django-templates

我在尝试访问现有模板时得到了这个:

Template-loader postmortem

Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
Using loader django.template.loaders.app_directories.Loader:
/blah-blah/venv3.4/lib/python3.4/site-packages/django/contrib/admin/templates/polymer.html (File does not exist)
/blah-blah/venv3.4/lib/python3.4/site-packages/django/contrib/auth/templates/polymer.html (File does not exist)

这是一个全新的项目,由于缺乏更好的地方,我将模板放在顶部目录中:

├── manage.py
├── polymertest
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── views.py
│   └── wsgi.py
├── static
│   ├── bower_components
│   └── polymer
└── templates
    └── polymer.html

我可以通过将os.path.join(BASE_DIR, 'templates')添加到settings.TEMPLATES['DIRS']

来解决问题
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        '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',
            ],
        },
    },
]

这对我来说确实很可疑,但根据documentation,这是预期的行为:您需要配置DIRS。我的问题是:

我应该将模板放在一个全新的Django项目中,以便filesystem.Loader无需配置即可找到它们?或者这根本不可能?

这对我来说似乎是一个常见的用例:创建项目,添加模板,添加视图和繁荣,提供服务!我很惊讶它不会被自动覆盖。

1 个答案:

答案 0 :(得分:1)

对于使用./manage.py startproject创建的设置文件,APP_DIRS选项为True。这意味着当您创建应用程序时,将找到该应用程序模板目录中的所有模板。

DIRS选项默认为空列表。这意味着除了app模板目录之外,没有任何模板目录在没有配置更改的情况下始终有效。

设置'DIRS': [os.path.join(BASE_DIR, 'templates')],是一种常见方法,它是suggested in the documentation