[Django]如何使用相对路径加载模版

模版的路径设置在settings.py中修改TEMPLATE_DIRS的值即可。

Django自带的注释说明如下:

# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.

也就是说Django是不推荐使用相对路径的。

那部署到站点的时候如何使用相对路径来加载模版呢?

可以用一下方式:

import os.path

TEMPLATE_DIRS = (

os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),

)

那么此时Django会加载的路径,就是该settings.py文件所在的目录下的templates文件夹。


举个例子,比如我的站点部署如下:

[Django]如何使用相对路径加载模版_第1张图片

只需要稍作修改即可:

import os.path
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), '../templates').replace('\\','/'),
)

你可能感兴趣的:([Django]如何使用相对路径加载模版)