Suppose you started your project using the django-admin startproject my_new_app
command, then it creates a hierarchy as follows.
my_new_app
|
└───my_new_app
│ │
│ │ settings.py
│ │ ...
| manage.py
Then, os.path.abspath(__file__)
returns the absolute path to the settings.py
file, os.path.dirname(os.path.abspath(__file__))
returns the path to the inner my_new_app
folder and os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
returns the path to the outer my_new_app
folder.
In more recent versions of Django (e.g. version 4.2.5), instead of os
, pathlib
module is used, so an equivalent construct is:
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
PROJECT_ROOT = Path(__file__).resolve().parent
There's a special case where if settings.py
is already in the root directory on your environment (e.g. the C drive on a local machine) so that its path looks like C:\settings.py
, then BASE_DIR == PROJECT_ROOT
may be True. This is probably not how it should be, so if BASE_DIR and PROJECT_ROOT are the same, then you probably need to re-structure your project.