【Django】关于模板设置的问题

在使用Django4.0时,在settings.py文件中指定templates目录时遇到了一点问题,我将它记录下来。

版本

Django版本为4.0.4,Python版本为3.10.2。

挫折点

首先,您可以通过创建一个名为 templates 的目录,在该目录中存放 HTML 文件,并可以在 views.py 文件中调用这些 HTML 文件。
但是,在使用 templates 目录之前,您需要在 settings.py 文件中指定 templates 的位置。

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',
            ],
        },
    },
]

由于”DIRS:[]”部分为空,我们将在这里进行记录。
虽然可以直接将终端输入”pwd”的位置进行记录,
但是这只适用于自己的终端,但在部署时以个人位置记录会引发错误。
因此,需要按照以下方式进行操作。

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [ BASE_DIR + '/templates'],

“BASE_DIR是在settings.py文件的开头定义的,它表示此项目的所在位置。所以,我认为如果我们加上+号,就可以得到一个合适的路径。因此,我将其如上所述写下来。”

在这里运行runserver会出现以下错误日志。

    'DIRS': [ BASE_DIR + '/templates'],
TypeError: unsupported operand type(s) for +: 'PosixPath' and 'str'

看起来BASE_DIR似乎不是一个字符串。
因此通过str()函数将其转换为字符串。

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [ str(BASE_DIR) + '/templates'],

我在这里解决了错误,所以问题解决了。
虽然我不确定这是否是正确的方法,
但问题已经解决,我将继续学习Django。

以上。