Template directory logic in Django

django, python

Solution

You ask, "why does django default to the second code example?" but in Django 1.5, when I run

$ django-admin.py startproject mysite

I find that `settings.py` contains:

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

so I am not sure where your example code is coming from: it's not Django's default.

On non-Windows systems it would be very rare to find backslashes in directory names, so your second example is likely to work in all practical cases. If I had to bullet-proof it I would write:

import os
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
if os.sep != '/':
    # Django says, "Always use forward slashes, even on Windows."
    TEMPLATE_DIR = TEMPLATE_DIR.replace(os.sep, '/')
TEMPLATE_DIRS = (TEMPLATE_DIR,)

(Using the names `os.pardir` and `os.sep` to make it clear what I intend.)

Problem

I've been fooling around with templates for some time now, and I am loving every moment of the django experience. However, since django is such a big fan loose coupling, I wanted to know, why not have this piece of code: ``` import os import platform if platform.system() == 'Windows': templateFiles = os.path.join(os.path.dirname(__file__), '..', 'templates').replace('\\','/') else: templateFiles = os.path.join(os.path.dirname(__file__), '..', 'templates') TEMPLATE_DIRS = ( # This includes the templates folder templateFiles, ) ``` instead of: ``` import os TEMPLATE_DIRS = ( templateFiles = os.path.join(os.path.dirname(__file__), '..', 'templates').replace('\\','/') ) ``` Would not the first example follow the philosophy of loose coupling better than the second (which I believe it does), and if so, why does django default to the second code example and not the first?

Original source