Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get absolute path of django app

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?

like image 789
tamakisquare Avatar asked Mar 23 '12 23:03

tamakisquare


People also ask

How do you find the absolute path?

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.

How do you find the absolute path of a path in Python?

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.

What is Base_dir in Django?

BASE_DIR is your Django project directory. The same directory where manage.py is located.


2 Answers

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.)

like image 91
Danica Avatar answered Sep 18 '22 14:09

Danica


So the accepted answer usually works fine. However, for

  • namespace packages with multiple paths, or
  • apps which explicitly configure their paths in the config,

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.

like image 28
thclark Avatar answered Sep 18 '22 14:09

thclark