Will & Skill Developers

Will & Skill Developers


Thoughts, snippets and ideas from the team at Will & Skill AB, Stockholm.

Faisal Mahmud
Author

“The mind is not a vessel to be filled, but a fire to be kindled.” ― Plutarch

Share


Smarter paths in Django settings.py

Faisal MahmudFaisal Mahmud

A good way to start a Django project is to set reasonable paths in order to avoid redundant code.

I have found that the folders where you store aggregated static files and user generated media should always be kept outside your git repo for the purpose of convenience when you compile stuff with tools such as Less, Sass, Gulp or Grunt.

Below are a few examples that You can use to upgrade your Django mojo!


# The directory where manage.py resides
PROJECT_DIR = os.path.dirname(os.path.dirname(__file__))
# The root of the git repo
# Could be ~/project or ~/repo
REPO_DIR = os.path.realpath(os.path.join(PROJECT_DIR, '..'))
# The directory of the current user ie /home/django a.k.a. ~
HOME_DIR = os.path.realpath(os.path.join(REPO_DIR, '..'))
# The directory where collectstatic command copies/symlinks the files to
# This can/should be located at ~/staticfiles, preferrably outside the git repo
STATIC_DIR = os.path.realpath(os.path.join(HOME_DIR, 'staticfiles'))
# The directory where different applications uploads media files to
# This can/should be located at ~/media, preferrably outside the git repo
MEDIA_DIR = os.path.realpath(os.path.join(HOME_DIR, 'media'))

It is then a lot simpler to refer to proper paths further down the road...

Example 1: STATICFILES_DIRS

STATICFILES_DIRS = (
    os.path.join(REPO_DIR, "assets"),
)

Example 2: STATIC_ROOT

STATIC_ROOT = os.path.join(REPO_DIR, "staticfiles")

Example 3: STATIC_ROOT

MEDIA_ROOT = os.path.join(HOME_DIR, "media")

Example 4: Accessing these values from some other module

from django.conf import settings
def build_path(filename):
    return "{}/{}".format(settings.MEDIA_ROOT, filename)

Happy coding!

Faisal Mahmud
Author

Faisal Mahmud

“The mind is not a vessel to be filled, but a fire to be kindled.” ― Plutarch

Comments