代码之家  ›  专栏  ›  技术社区  ›  cindy50633

Django'DIRS':[]在settings.py TEMPLATES中导致“TemplateDoesNotExist”错误

  •  0
  • cindy50633  · 技术社区  · 6 年前

    我将django版本2.1.2与Python3.6结合使用。

    两个项目都在同一文件夹下。 Test01正常执行,而test02引发TemplateDoesNotExist错误。 enter image description here

    我为后者找到了一个解决方案,即在settings.py中硬编码模板的地址:

    但是,即使将此列表保留为空[],另一个项目也可以正常运行。

    两个项目的结构相同: enter image description here

    有没有人能给出一个建议来解决test02中的问题,而不必硬编码test02中模板的地址?

    2 回复  |  直到 6 年前
        1
  •  3
  •   Lemayzeur    6 年前

    BASE_DIR ,它表示根项目,因此不需要硬编码绝对路径。

    将此添加到设置中

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    # codes...
                ],
            },
        },
    ]

    注册你所有的应用程序,Django就会在一个名为 templates os.path.join(BASE_DIR, 'templates')

        2
  •  1
  •   Cuong DaoVan    6 年前

    让我们在template中创建一个名为“test01App”的文件夹,并在其上创建base.html。
    后端是默认的django,你必须创建文件夹“模板”。 您可以在目录的其他位置自定义where store模板。

    TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, './cuong')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
    

    ]