如何正确设置Django模板路径?

时间:2020-09-11 09:46:27

标签: python django django-templates python-3.8 django-3.1

在最新的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。

2 个答案:

答案 0 :(得分:2)

要使用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__)))

答案 1 :(得分:0)

谢谢

from pathlib import Path 
import os

BASE_DIR = Path(__file__).resolve().parent.parent
相关问题