简体   繁体   English

Django模板的相对路径

[英]Django templates relative path

import os.path

BASE_DIR = os.path.dirname(os.path.dirname(__file__))

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

I want to know what exactly the TEMPLATE_DIRS is , so i run it on the Django shell, 我想知道TEMPLATE_DIRS到底是​​什么,所以我在Django shell上运行它,

>>> import os.path
>>> os.path.dirname(__file__)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name '__file__' is not defined

Why such kind of legal attribute failed in shell? 为什么这种法律属性在shell中失败了? I did do some test in shell and came another question: 我确实在shell中做了一些测试,然后出现了另一个问题:

>>> os.path.dirname(os.path.dirname('/user/name'))
'/'
>>> os.path.dirname('/user/name')
'/user'
>>> B = os.path.dirname(os.path.dirname('/user/name'))
>>> os.path.join(B,'template')
'/template'

The code with comment, os.path.join(BASE_DIR,'templates') , doesn't it come out with '/templates' ? 带注释的代码os.path.join(BASE_DIR,'templates') ,不是带有'/templates'吗? Isn't that a root directory? 那不是根目录吗? If that, how can Django search my templates files in a directory that even i don't have it? 如果是这样,Django如何在我什至没有的目录中搜索我的模板文件?

The variable __file__ doesn't exist in a Python shell. 变量__file__在Python Shell中不存在。 So you can't just test the value like that. 因此,您不能仅仅测试像这样的值。

The BASE_DIR value will be equal the parent folder of the file where the line is situation. BASE_DIR值将等于所在行所在文件的父文件夹。 If you have a Django project and the line is in /home/xyz/foo/foo/settings.py , then BASE_DIR is equal to /home/xyz/foo . 如果您有Django项目,并且该行位于/home/xyz/foo/foo/settings.py ,则BASE_DIR等于/home/xyz/foo

Why? 为什么? __file__ returns the absolute path of the current file, here, our settings.py . __file__返回当前文件的绝对路径,这里是我们的settings.py After, you are taking two times the folder. 之后,您将获得两倍的文件夹。 The first time it will take /home/xyz/foo/foo/ (it removes the file name in the path) and the second time it will take the parent folder. 第一次使用/home/xyz/foo/foo/ (删除路径中的文件名),第二次使用文件夹。 Hence, we arrive to the project main folder. 因此,我们到达项目主文件夹。

Also, you don't need to replace \\\\ by / since the Python os.path module know how to deal with this according to your current OS. 另外,您不需要用/替换\\\\ ,因为Python os.path模块知道如何根据您当前的OS处理此问题。

In summary, your current line point to a templates/ directory at the root of your Django project :) 总而言之,您当前的行指向Django项目根目录下的templates/目录:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM