这真让我抓狂。我做了一些奇怪的事情,看来我的TEMPLATE_DIRS条目被忽略了。我在项目目录中只有一个settings.py文件,它包含:

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

我将项目级模板放在/templates文件夹中,然后在我的app文件夹中包含用于不同 View 类别的文件夹(例如,身份验证 View ,帐户 View 等)。

例如,我的主索引页面 View 在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)

为什么世界上都没有搜索"template"和“web_app/views”目录?我已经通过调试器和views_main.py中的一个断点检查了“设置”,看起来它们就在其中。有人遇到过类似的问题吗?谢谢。

最佳答案

您正在使用哪个版本的Django?自 1.8 起,不推荐使用TEMPLATE_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/

关于python - Django 1.8 TEMPLATE_DIRS被忽略,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30262343/

10-09 07:26
查看更多