【问题标题】:Django 1.8 TEMPLATE_DIRS being ignoredDjango 1.8 TEMPLATE_DIRS 被忽略
【发布时间】:2015-05-15 14:41:03
【问题描述】:

这快把我逼疯了。我做了一些奇怪的事情,似乎我的 TEMPLATE_DIRS 条目被忽略了。我只有一个 settings.py 文件,位于项目目录中,它包含:

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'),
    os.path.join(BASE_DIR, 'web_app/views/'),
)

我将项目级模板放在 /templates 文件夹中,然后在我的应用程序文件夹中有用于不同视图类别的文件夹(例如身份验证视图、帐户视图等)。

例如,我的主索引页面视图位于 web_app/views/main/views_main.py 中,看起来像

from web_app.views.view_classes import AuthenticatedView, AppView


class Index(AppView):
    template_name = "main/templates/index.html"

AppView 只是 TemplateView 的扩展。这是我的问题:当我尝试访问该页面时,我得到一个 TemplateDoesNotExist 异常,而真正让我困惑的部分是 Template-Loader Postmortem:

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:
C:\Python34\lib\site-packages\django\contrib\admin\templates\main\templates\index.html (File does not exist)
C:\Python34\lib\site-packages\django\contrib\auth\templates\main\templates\index.html (File does not exist)

为什么不搜索“模板”和“web_app/views”目录?我已经通过调试器和views_main.py 中的断点检查了设置,看起来它们就在那里。有没有人遇到过类似的问题?谢谢。

【问题讨论】:

    标签: python django


    【解决方案1】:

    您使用的是哪个版本的 Django? TEMPLATE_DIRS1.8

    起已弃用

    自 1.8 版起已弃用: 改为设置 DjangoTemplates 后端的 DIRS 选项。

    https://docs.djangoproject.com/en/1.8/ref/settings/#template-dirs

    所以试试这个吧:

    TEMPLATES = [
      {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            # insert your TEMPLATE_DIRS here
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                # Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
                # list if you haven't customized them:
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    
      },
    ]
    

    这是升级指南的链接:https://docs.djangoproject.com/en/1.8/ref/templates/upgrading/

    【讨论】:

    • 是的。就是这样。那是两个小时的可靠使用。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 2012-09-09
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    相关资源
    最近更新 更多