I am writing a unit test that needs to access an image file that I put in "fixtures" directory right under my django app directory. I want to open up this image file in my test using relative path, which would require me to get the absolute path of the django app. Is there a way to get the absolute path of the django app?
To find the full absolute path of the current directory, use the pwd command. Once you've determined the path to the current directory, the absolute path to the file is the path plus the name of the file.
Use abspath() to Get the Absolute Path in Pythonpath property. To get the absolute path using this module, call path. abspath() with the given path to get the absolute path. The output of the abspath() function will return a string value of the absolute path relative to the current working directory.
BASE_DIR is your Django project directory. The same directory where manage.py is located.
Python modules (including Django apps) have a __file__
attribute that tells you the location of their __init__.py
file on the filesystem, so
import appname pth = os.path.dirname(appname.__file__)
should do what you want.
In usual circumstances, os.path.absname(appname.__path__[0])
, but it's possible for apps to change that if they want to import files in a weird way.
(I do always do PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
in my settings.py
, though -- makes it easy for the various settings that need to be absolute paths.)
So the accepted answer usually works fine. However, for
their intended path may not agree with the __file__
attribute of the module.
Django (1.7+) provides the AppConfig.path
attribute - which I think is clearer even in simple cases, and which covers these edge cases too.
The application docs tell you how to get the AppConfig object. So to get AppConfig and print the path from it:
from django.apps import apps print(apps.get_app_config('app_label').path)
Edit: Altered example for how to use get_app_config
to remove dots, which seems to have been confusing. Here are the docs for reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With