Get absolute path of django app

怎甘沉沦 提交于 2019-12-02 21:57:05

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

Normally, this is what I add in my settings.py file so I can reference the project root.

import os.path

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))

This method will get the directory of any python file.

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('your.app.name').path)

Keep in mind that appname.__path__ is a list:

import appname
APP_ROOT = os.path.abspath(appname.__path__[0])
file_path = os.path.join(APP_ROOT, "some_file.txt")

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!