【问题标题】:Django Templates: How does it decide where to load a template?Django 模板:它如何决定在哪里加载模板?
【发布时间】:2014-12-30 17:00:53
【问题描述】:
我一直在关注 Django Girls 教程,直到我们添加了登录功能,我已经到了它尝试从我想要的不同模板文件夹加载的地步。
我的所有博客模板都在 blog\templates\blog\ 等中,这就是 Django 正在寻找我的 login.html 的地方。但是,在本教程(以及我的文件夹结构中)中,login.html 的路径是:mysite/templates/registration/login.html。那么如何让 Django 看起来呢?
对不起,如果这是一个愚蠢的问题。
【问题讨论】:
标签:
django
django-templates
【解决方案1】:
Django 将查看您的settings.py 以了解如何加载模板,以及它应该尝试加载模板的顺序。很可能你没有配置 django 在 mysite/templates 中查找模板。
有一个名为TEMPLATE_DIRS 的设置是模板文件夹的绝对路径列表。因此,在您的 settings.py 文件中,尝试如下操作。阅读我的 cmets 以了解每一行的作用。
# create a variable that stores the absolute path to your project's root directory
# you might have something like this already defined at the top of your settings.py
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
# this is the default value for TEMPLATE_LOADERS
# which says to look at the `TEMPLATE_DIRS` variable, and then in each of your app's subdirectories for templates
TEMPLATE_LOADERS = ('django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader')
# the special sauce. tell django to look at the "templates" folder
TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'), )