[Django]-Using django.setup() from a subdirectory, how to reference settings?

9👍

You can use this function, that i use commonly to run script from outside django.

def __setup_django(root_path, settings):
    import os
    import django

    os.chdir(root_path)

    # Django settings
    sys.path.append(root_path)
    os.environ['DJANGO_SETTINGS_MODULE'] = settings

    django.setup()

PROJECT_PATH = "/home/a/b/c/someproject"
PROJECT_SETTING = "someproject.settings.local"

__setup_django(PROJECT_PATH, PROJECT_SETTING)

1👍

Simply set PYTHONPATH when you run your script.

PYTHONPATH=/app DJANGO_SETTINGS_MODULE=app.settings /script.py

PYTHONPATH is akin to PATH, a colon delimited list of directories python uses to import modules.

Leave a comment