Django Relative Path for

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

From Jeff Hui @ Nettuts: (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 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 file to fetch the relative path to your app like so:


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


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__))

     PROJECT_ROOT + "/templates/",

If i was worried about slashes I suppose something like:


 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:
  • Sahas Katta

    I’m doing the following:

    TEMPLATE_DIRS = (‘./templates’, )

    Is there any drawback to my method?

    (I’m new to Django)

    • Cory

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

      • 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

        • Cory

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