【问题标题】:Django Template inheritance (location for extends)Django 模板继承(扩展的位置)
【发布时间】:2016-05-27 20:30:26
【问题描述】:

我正在尝试创建 base.html 以从我的应用程序中扩展它。

我的结构:

ROOT(pyshop)

  • 投票
    • 模板
      • 投票
        • index.html(包含 {% extends "base.html" %})
  • pyshop
    • 模板
      • base.html

但是找不到base.html

模板加载器事后分析

Django 尝试按以下顺序加载这些模板:

使用引擎 django: django.template.loaders.app_directories.Loader: /home/sz/Projects/pyshop/polls/templates/pyshop/base.html (来源不存在) django.template.loaders.app_directories.Loader:/home/sz/Projects/pyshop/venv/lib/python3.5/site-packages/django/contrib/admin/templates/pyshop/base.html(源不存在) django.template.loaders.app_directories.Loader:/home/sz/Projects/pyshop/venv/lib/python3.5/site-packages/django/contrib/auth/templates/pyshop/base.html(源不存在)

有什么建议吗?

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    应用目录加载器不会搜索您的pyshop/pyshop/templates 目录,因为它不是应用程序。通常的做法是将此目录添加到DIRS 列表中。

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'pyshop', 'templates'),]
        ...
        }
    ]
    

    其次,回溯使您看起来好像在做{% extends "pyshop/base.html" %},而不是您的问题中的{% extends "base.html" %}。如果您有{% extends "base.html" %},那么您需要将您的base.html 模板移动到pyshop/pyshop/templates/pyshop/base.html

    【讨论】:

    • 感谢您的回答。设置 DIRS 解决我的问题!关于 {% extends "pyshop/base.html" %} 我发布了错误的回溯,我尝试了很多不同的变体 :)
    • app_dirs 是真的,但它没有帮助。
    • 'APP_DIRS': True 表示它将在您的INSTALLED_APPS 设置中搜索每个应用程序的模板目录。但是,pyshop/pyshop 目录(包含settings.py 等)通常不会添加到INSTALLED_APPS,因此'APPS': True 没有帮助。因此,您将目录添加到 DIRS
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 2010-12-23
    • 2010-11-27
    相关资源
    最近更新 更多