[英]How to set Django template path properly?
In most recent django documentation "Overriding from the project's templates directory" https://docs.djangoproject.com/en/3.1/howto/overriding-templates/ it shows that you can use the following path for templates:在最新的 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,
...
},
]
I tried using [BASE_DIR / 'templates']
but I keep getting the following error:我尝试使用[BASE_DIR / 'templates']
但我不断收到以下错误:
TypeError: unsupported operand type(s) for /: 'str' and 'str'
It all works fine when I change the code to: [BASE_DIR , 'templates']
or [os.path.join(BASE_DIR , 'templates')]
, no problem in such case.当我将代码更改为: [BASE_DIR , 'templates']
或[os.path.join(BASE_DIR , 'templates')]
,一切正常,在这种情况下没问题。
Can someone explain what am I missing with the [BASE_DIR / 'templates']
line?有人可以解释我在[BASE_DIR / 'templates']
行中遗漏了什么吗? Thank you.谢谢你。
I'm using Python 3.8 and Django 3.1.我正在使用 Python 3.8 和 Django 3.1。
In order to use BASE_DIR / 'templates'
, you need BASE_DIR
to be a Path()
.为了使用BASE_DIR / 'templates'
,您需要BASE_DIR
成为Path()
。
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
I suspect that your settings.py was created with an earlier version of Django, and therefore BASE_DIR
is a string, eg我怀疑你的 settings.py 是用早期版本的 Django 创建的,因此BASE_DIR
是一个字符串,例如
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Thank you谢谢
from pathlib import Path
import os
BASE_DIR = Path(__file__).resolve().parent.parent
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.