Django requires you to define different file paths in the settings, such as the root of your media, the root of your static files, the path to templates, and the path to translation files. For each developer of your project, the paths may differ as the virtual environment can be set up anywhere and the user might be working on macOS, Linux, or Windows. Even when your project is wrapped in a Docker container, it reduces maintainability and portability to define absolute paths. In any case, there is a way to define these paths dynamically so that they are relative to your Django project directory.
Defining relative paths in the settings
Getting ready
Have a Django project started, and open settings.py.
How to do it...
Modify your path-related settings accordingly, instead of hardcoding the paths to your local directories, as follows:
# settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# ...
TEMPLATES = [{
# ...
DIRS: [
os.path.join(BASE_DIR, 'templates'),
],
# ...
}]
# ...
LOCALE_PATHS = [
os.path.join(BASE_DIR, 'locale'),
]
# ...
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'site_static'),
]
FILE_UPLOAD_TEMP_DIR = os.path.join(BASE_DIR, 'tmp'
How it works...
By default, Django settings include a BASE_DIR value, which is an absolute path to the directory containing manage.py (usually one level higher than the settings.py file). Then, we set all of the paths relative to BASE_DIR using the os.path.join function.
Based on the directory layout we set down in the Creating a virtual environment project file structure recipe, we would insert 'myproject' as an intermediary path segment for each of the previous examples, since the associated folders were created within that one. For Docker projects, as shown in the Creating a Docker project file structure recipe, we set the volumes for media, static, and so forth to be alongside manage.py in BASE_DIR itself.
See also
- The Creating a virtual environment project file structure recipe
- The Creating a Docker project file structure recipe
- The Including external dependencies in your project recipe