Django 查找 templates 时设置 'DIRS' 路径的问题?

我的主项目目录下,和 APP 目录下都有 templates 文件夹,为了让 Django 能找到模板,我看很多资料,包括官方 tutorial 里面都是说要把 settings 设置里面,TEMPLATES 的 'DIRS' 设置如下:

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

这样就明确了去项目根目录下的 templates 文件夹中找。

但是我发现,路径只填一个'templates'也可以:

TEMPLATES = [{
    'DIRS': ['templates'],
}]

效果一样,也能成功在项目根目录下的 templates 文件夹中找到模板文件。

所以我的问题是,为什么只填一个'templates'也行呢?也能代表根目录下的 templates 呢?另外为什么所有资料都没提到能这样简写呢,这样写是会有什么坑吗?

新手初学,多谢指教!

阅读 4.3k
1 个回答

源码里是这么实现位置查找的

class EngineMixin:
    def get_template(self, template_name):
        return self.engine.get_template(template_name)

    @cached_property
    def engine(self):
        return self.backend({
            'APP_DIRS': True,
            'DIRS': [os.path.join(ROOT, self.backend.app_dirname)],
            'NAME': 'djangoforms',
            'OPTIONS': {},
        })


[docs]class DjangoTemplates(EngineMixin, BaseRenderer):
    """
    Load Django templates from the built-in widget templates in
    django/forms/templates and from apps' 'templates' directory.
    """

    backend = DjangoTemplates


import django
django.__path__[0] + '/forms/templates'
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题