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?
相关问题
- Django __str__ returned non-string (type NoneType)
- Django & Amazon SES SMTP. Cannot send email
- Django check user group permissions
- Django restrict pages to certain users
- UnicodeEncodeError with attach_file on EmailMessag
相关文章
- Profiling Django with PyCharm
- Why doesn't Django enforce my unique_together
- MultiValueDictKeyError in Django admin
- Django/Heroku: FATAL: too many connections for rol
- Django is sooo slow? errno 32 broken pipe? dcramer
- Django: Replacement for the default ManyToMany Wid
- Upgrading transaction.commit_manually() to Django
- UnicodeEncodeError when saving ImageField containi
Normally, this is what I add in my settings.py file so I can reference the project root.
This method will get the directory of any python file.
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:
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.În newer versions of Django (I don't know when it started, I assume it's there for many years now), the default settingy.py contains an entry
which you can use by importing the settings file like this
Keep in mind that
appname.__path__
is a list:Python modules (including Django apps) have a
__file__
attribute that tells you the location of their__init__.py
file on the filesystem, soshould 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 mysettings.py
, though -- makes it easy for the various settings that need to be absolute paths.)Python3.4 and above comes with standard library
pathlib
.parent
will give you the path of your app directory, and/
will append fixtures as path.