Search code examples
pythondjangoheroku

How to have different settings.py locally and in production


I want to have different settings.py for when I run my project locally and in production, because I have a setting in settings.py that forces my project to use https, but django runserver.py can only use http, not https, so I am unable to run my project locally now. Also, I want to have debug=True on my computer, and debug=False in production. So how can I have a different settings.py for my computer and for production?


Solution

  • There are some options, one these to create two settings files:

    add the following to the end of your settings.py:

    import os
    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    PROJECT_APP_PATH = os.path.dirname(os.path.abspath(__file__))
    PROJECT_APP = os.path.basename(PROJECT_APP_PATH)
    BASE_DIR = os.path.dirname(PROJECT_APP_PATH)
    
    DEBUG = False
    ...
    
    ...
    
    ##################
    # LOCAL SETTINGS #
    ##################
    
    # Allow any settings to be defined in local_settings.py which should be
    # ignored in your version control system allowing for settings to be
    # defined per machine.
    
    f = os.path.join(PROJECT_APP_PATH, "local_settings.py")
    if os.path.exists(f):
        import sys
        import imp
        module_name = "%s.local_settings" % PROJECT_APP
        module = imp.new_module(module_name)
        module.__file__ = f
        sys.modules[module_name] = module
        exec(open(f, "rb").read())
    

    Create local_settings.py and overwrite the desired settings:

    #####################
    # OVERWRITE SETTINGS #
    #####################
    
    DEBUG = True
    SECURE_PROXY_SSL_HEADER = None
    SECURE_SSL_REDIRECT = False
    
    
    ...