Django 不搜索 APP_DIRS 设置中定义的模板目录

问题描述 投票:0回答:6

我有一个与我的项目目录处于同一级别的模板目录,所以我放入了settings.py

'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,

但是 Django 不会在应用程序中搜索模板,它会在 DIRS 处停止

安装了所有需要的应用程序

python django django-templates django-settings
6个回答
8
投票

我的解决方案是将应用程序名称放在 INSTALLED_APPS 的末尾

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'posts'  # <= put your app name here i guess?
]

2
投票

我今天得到了这个(我使用的是 django 2.1)。解决方案是将“myappname”添加到设置中的 INSTALLED_APPS 中(以前您必须在较旧的 django 版本上执行此操作,但我认为不再是强制性的)。如果不这样做,django 模板处理器就不会查找 myappname/templates/myappname/

我也像其他一些答案一样设置了 TEMPLATES_DIRS ,但无论出于何种原因,这对我当前的设置来说是不够的(我打破了我的笔记本电脑,所以我在 Windows 上使用全新的 python 3.7 和全新的 django 2.1 (大约一周前我上次使用 django 时不必执行此步骤...)


1
投票

检查您的

DIRS
设置。它应该包括模板目录本身。

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

        # True or False, depends on your case.
        'APP_DIRS': True,

        # Default django setup.
        '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',
            ],
        },
    },
]

0
投票

只需将模板目录的名称放在 settings.py 中“DIRS”部分的 TEMPLATES 数组下即可

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['your folder name'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'logyt_transporte.context_processors.module_variables',
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

0
投票

我试图覆盖第三方包中的模板。

我的问题是我按以下顺序有

INSTALLED_APPS

INSTALLED_APPS = [
    # core
    # third-party
    # mine
]

因为我清楚地掩盖了文档,它告诉你这不是它的工作原理:https://docs.djangoproject.com/en/3.1/ref/settings/#installed-apps

特别是最后一行:

当多个应用程序提供相同版本的不同版本时 资源(模板、静态文件、管理命令、翻译)、 INSTALLED_APPS 中首先列出的应用程序具有优先权。

将其视为后备顺序,并确保覆盖在原始顺序之前,瞧。叹息。


0
投票
('polls/templates/polls/index.html')

,那么您应该在模板文件中包含您的应用程序名称,如下所示:

loader.get_template("polls/index.html")

© www.soinside.com 2019 - 2024. All rights reserved.