python - 如何正确设置 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。
解决方案
为了使用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__)))
推荐阅读
- scala - Substract two dates in Scala with yyyyMMdd format
- python - Or | 的奇怪行为 运算符和非
- mysql - 为什么select语句在mysql的存储过程中显示前一个select语句的结果集
- algorithm - 如何选择距离最远的k个元素
- angular - 我应该为 Angular 中的模板可访问方法提供什么样的访问修饰符?
- javascript - 从 Bokeh 交互式线图中的 ColumnDataSource 中选择行
- javascript - 如何使用 createMaterialTopTabNavigator 作为组件
- javascript - javascript承诺处理,无法处理错误
- css - 在 CSS 网格模板中使用 sass 变量
- javascript - 未捕获的类型错误:无法读取未定义的属性“0” - 在 Leaflet .eachLayer 函数中