Django 中模板和静态文件的“DIRS”属性的使用

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

我对 Django 和后端开发总体来说是新手。我目前正在尝试构建一个非常简单的应用程序。我看了一些教程,对两件事有点困惑:

1. 图中下面的属性

DIRS
有什么用?我知道它以某种方式用于“注册”模板,但在我自己的应用程序中,我没有注册它,但不知何故它仍然正常工作。

这是我的settings.py中TEMPLATES中DIRS属性的代码:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [], 
        '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',
            ],
        },
    }, ]

这是我的项目的结构:

Project_structure

(抱歉,因为我没有足够的声誉,所以没有直接有图像给您带来不便)

2. “部署”静态文件是什么意思?为什么它比让 Django 自己自动“部署”文件更好?这是文档的链接,其中他们解释了为什么我们需要提供/部署静态文件(在“提供文件”注释中):https://docs.djangoproject.com/en/5.0/howto/static-files /

我真的很感谢对事情如何运作的任何详尽解释,因为我是初学者。如果你们也提供任何 Django 实践资源,我将不胜感激!

django django-templates
1个回答
0
投票

DIRS
是一组可选路径,Django 应首先在其中查找要渲染的模板。 文档

APP_DIRS
如果启用,Django 将在每个应用程序的
templates
子文件夹中查找要渲染的模板。 文档

覆盖 blog

 应用程序 
blog/templates/blog/...
 文件夹中模板的示例
,其中模板存储在附加
<BASE_DIR>/additional_templates
文件夹中。

INSTALLED_APPS = [
    ...,
    "blog",
    ...,
]

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / "additional_templates"],
        "APP_DIRS": True,
        # ...
    },
]

如果你调用

render(request, 'blog/profile.html')
,Django会首先尝试在
<BASE_DIR>/additional_templates/blog/profile.html
位置找到这个模板,如果没有这样的文件,它会去博客应用程序文件夹并尝试找到
blog/templates/blog/profile.html

如果您没有位于其他地方的模板

<app_name>/templates
那么您不需要定义
DIRS
参数。这就是模板渲染在您的项目中起作用的原因。您的模板位于 jobs 应用程序文件夹中:
jobs/templates/index.html
APP_DIRS
已启用,无需任何其他操作。

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