首页 > 解决方案 > 如何正确设置 Django 模板路径?

问题描述

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

标签: pythondjangodjango-templatespython-3.8django-3.1

解决方案


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

推荐阅读