Django Relative Path for settings.py

by on February 20, 2012 in
Django Relative Path for settings.py Difficulty Level: Beginner
 

From Jeff Hui @ Nettuts: http://net.tutsplus.com/tutorials/python-tutorials/diving-into-django/ (7:30) with .replace(‘\\’,’/’) added on so Windows backslashy directories are fixed (Django doesn’t like that sorta thing).

Just put this around the top of your settings.py file:

import os
def relative_project_path(*x):
    return os.path.join(os.path.abspath(os.path.dirname(__file__)), *x)

Then use it throughout your settings.py file to fetch the relative path to your app like so:

TEMPLATE_DIRS = (
    relative_project_path('templates'),
)

This example would target /home/User/Project/my_django_app/templates/

Updates

kezabelle suggests

I have, in 2+ years of having to work with Django in a Windows environment, never had to replace backslashes.
Specifically, I’ve always just done:

PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
TEMPLATES_DIR = os.path.join(PROJECT_PATH, 'templates')

Apparently, YMMV.

dysmas suggests

I tend to do something like

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

TEMPLATE_DIRS = (
     PROJECT_ROOT + "/templates/",
)

If i was worried about slashes I suppose something like:

TEMPLATE_DIRS =  (
       "templates",
 )

 TEMPLATE_DIRS = [os.path.join(PROJECT_ROOT, path) for path in TEMPLATE_DIRS]

n.b. just typed the above off the top of my head.

Verslaafde explains

If you use the os.path functions, backslash/slash conversions are done for you.

 
If you liked this article, you might also like:
  • http://sahaskatta.com/ Sahas Katta

    I’m doing the following:

    TEMPLATE_DIRS = (‘./templates’, )

    Is there any drawback to my method?

    (I’m new to Django)

    • http://pressedweb.com/ Cory

      Does that work on localhost? Newb question here: What does the . do exactly?

      • http://sahaskatta.com/ Sahas Katta

        Works on local host. I am also new to this, so I would suggest using the method mentioned the article about until someone sheds light on my code

        • http://pressedweb.com/ Cory

          No way. Let’s start using your’s until someone tells us why it’s bad. That’s how good code is discovered. :)