7

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.

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This is the best answer, you can use slashes in windows and linux. Backslashes were the biggest issue I was having.
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.
@CraigTrader: it's a nice idea to use posixpath.join(), but that won't remove backslashes that are already in the path components being joined (e.g., from os.path.dirname(__file__).
2

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.

Comments

1

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 '\')

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.