Yugal Jindle
Yugal Jindle

Reputation: 45696

Why absolute paths to templates and css in django ? (Isn't that a bad practice ?)

In django, the documentation asks to use the absolute paths and not the relative paths.

Then, how do they manage portability ?

If I have my template in the project folder then, even a rename of the folder will cause breakage.. !

Then what is the reason behind this practice ?

Please explain ?

Upvotes: 0

Views: 619

Answers (2)

Brandon Taylor
Brandon Taylor

Reputation: 34573

I switch environments from a Linux desktop to a Windows laptop, so hard coding paths won't work for me either.

There may be a better way to do this, but I wrote this function that goes at the top of my settings.py to get the absolute path from a relative path in my project:

#settings.py
import os

def map_path(directory_name):
    return os.path.join(os.path.dirname(__file__), \
        directory_name).replace('\\', '/')

That allows me to do:

MEDIA_ROOT = map_path('static')
TEMPLATE_DIRS = (
    map_path('templates'),
)

"static" and "templates" live under my project root. Hope that helps you out.

Upvotes: 0

ftartaggia
ftartaggia

Reputation: 541

Could you post a link to that piece of documentation, please?

In Django you configure, in settings.py, the search path for templates (through TEMPLATE_DIRS variable). Then, inside a view, you render a template naming its file relative to one of the path included in TEMPLATE_DIRS. That way, whenever you move you template dir you just need to modify your settings.py

As for static files, like CSS docs, Django does not need to know anything about them (unless you are serving static files through django itself, which is discouraged by django's documentation): you only need to tell your web server where to find them.

Upvotes: 1

Related Questions