Django paths, developing in windows, deploying on linux

后端 未结 4 1035
悲哀的现实
悲哀的现实 2021-02-09 10:47

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

4条回答
  •  孤街浪徒
    2021-02-09 11:14

    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.

提交回复
热议问题