31
I’ll suggest you to use absolute path
but in a more clever way. Declare in your settings.py
something like XMLFILES_FOLDER
and have your settings.py
like this:
import os
settings_dir = os.path.dirname(__file__)
PROJECT_ROOT = os.path.abspath(os.path.dirname(settings_dir))
XMLFILES_FOLDER = os.path.join(PROJECT_ROOT, 'xml_files/')
This is assuming that xml_files
folder lives under the project root folder, if not, just declare the relative path from the project root folder to the xml_files
XMLFILES_FOLDER = os.path.join(PROJECT_ROOT, 'f1/f2/xml_files/')
That way, wherever in your code you want to access a file inside that directory you just do:
from settings import XMLFILES_FOLDER
path = XMLFILES_FOLDER+'area.xml'
This approach will work in any OS, and no matter you change the folder of the project, it will still work.
Hope this helps!
35
@Paulo Bu’s answer is correct, but outdated. Modern-day settings.py files have a BASE_DIR variable you can use for this endeavour.
import os
from yourproject.settings import BASE_DIR
file_path = os.path.join(BASE_DIR, 'relative_path')
Bear in mind that the relative path is from your Django project’s root folder.
- [Django]-How do I pass a PK or slug to a DetailView using RequestFactory in Django?
- [Django]-Django gunicorn sock file not created by wsgi
- [Django]-Timestamp fields in django
Source:stackexchange.com