tags:

views:

64

answers:

4

I'm developing Django apps on my local windows machine then deploying to a hosted linux server. The format for paths is different between the two and manually replacing before deployment is consuming more time than it should. I could code based on a variable in my settings file and if statements but I was wondering if anyone had best practices for this scenario.

+2  A: 

We have a situation very similar to yours, and we've been using different paths in settings, basing on sys.platform. Something like this:

import os, sys
DEVELOPMENT_MODE = sys.platform == 'win32'
if DEVELOPMENT_MODE:
    HOME_DIR = 'c:\\django-root\\'
else:
    HOME_DIR = '/home/django-root/'

It works quite OK - assumed all development is being done on Windows.

Roberto Liffredo
+1  A: 

Add

import os.path

BASE_PATH = os.path.dirname(__file__)

at the top of your settings file, and then use BASE_PATH everywhere you want to use a path relative to your Django project.

For example:

MEDIA_ROOT = os.path.join(BASE_PATH, 'media')

(You need to use os.path.join(), instead of simply writing something like MEDIA_ROOT = BASE_PATH+'/media', because Unix joins directories using '/', while windows prefers '\')

Ludwik Trammer
A: 

in your settings.py add the following lines

import os.path

SETTINGS_PATH = os.path.abspath(os.path.dirname(__file__))  
head, tail = os.path.split(SETTINGS_PATH)

#add some directories to the path
import sys
sys.path.append(os.path.join(head, "apps"))
#do what you want with SETTINGS_PATH
Pierre-Jean Coudert
+2  A: 

The Django book suggests using os.path.join (and to use slashes instead of backslashes on Windows):

import os.path

TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)

I think this is the best solution as you can easily create relative paths like that. If you have multiple relative paths, a helper function will shorten the code:

def fromRelativePath(*relativeComponents):
    return os.path.join(os.path.dirname(__file__), *relativeComponents).replace("\\","/")

If you need absolute paths, you should use an environment variable (with os.environ["MY_APP_PATH"]) in combination with os.path.join.

AndiDog
This is the best answer, you can use slashes in windows and linux. Backslashes were the biggest issue I was having.
marr75
You might want to use `posixpath.join()` instead of `os.path.join().replace()` -- it makes your intent clear: you want a POSIX-style path regardless of your OS.
Craig Trader