[英]How to set Django template path properly?
在最新的 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。
为了使用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__)))
谢谢
from pathlib import Path
import os
BASE_DIR = Path(__file__).resolve().parent.parent
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.