Question

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,

>>> 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? I did do some test in shell and came another question:

>>> 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'? 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?

Was it helpful?

Solution

The variable __file__ doesn't exist in a 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. 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.

Why? __file__ returns the absolute path of the current file, here, our 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. 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.

In summary, your current line point to a templates/ directory at the root of your Django project :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top