4

在最新的 django 文档“从项目的模板目录覆盖” https://docs.djangoproject.com/en/3.1/howto/overriding-templates/ 它表明您可以使用以下模板路径:

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

我尝试使用[BASE_DIR / 'templates']但我不断收到以下错误:
TypeError: unsupported operand type(s) for /: 'str' and 'str'

当我将代码更改为:[BASE_DIR , 'templates']或时,一切正常[os.path.join(BASE_DIR , 'templates')],在这种情况下没问题。
有人可以解释我在这[BASE_DIR / 'templates']条线上缺少什么吗?谢谢你。

我正在使用 Python 3.8 和 Django 3.1。

4

2 回答 2

6

为了使用BASE_DIR / 'templates',你需要BASE_DIR成为一个Path().

from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

我怀疑您的 settings.py 是用早期版本的 Django 创建的,因此BASE_DIR是一个字符串,例如

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
于 2020-09-11T10:22:49.773 回答
1

谢谢

from pathlib import Path 
import os

BASE_DIR = Path(__file__).resolve().parent.parent
于 2021-01-14T05:27:12.950 回答