Skip to content

Instantly share code, notes, and snippets.

@jordanorelli
Created June 14, 2011 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordanorelli/1025419 to your computer and use it in GitHub Desktop.
Save jordanorelli/1025419 to your computer and use it in GitHub Desktop.
Load Django environment for CLI script
#!/usr/bin/env python
# Load the Django environment
from django.core.management import setup_environ
import os
import sys
try:
project_path = os.environ['DJANGO_PROJECT_PATH']
except KeyError:
raise Exception("Unable to locate Django project. Set your operating "
"system's DJANGO_PROJECT_PATH environment variable to "
"point to the root of the Django project.")
if project_path not in sys.path:
sys.path.append(project_path)
settings_module = os.environ.get('DJANGO_SETTINGS_MODULE')
if settings_module:
settings = __import__(settings_module)
else:
import settings
setup_environ(settings)
# End Django environment load.
@jordanorelli
Copy link
Author

This script does nothing. It deliberately does nothing so that I can clone it and just add code at the end for Django CLI script. It requires, at minimum, the DJANGO_PROJECT_PATH environment variable be set. I also included an optional DJANGO_SETTINGS_MODULE variable that, if present, will be used as the settings module. E.g., running export DJANGO_SETTINGS_MODULE=settings_dev prior to invoking this script would be similar to ./manage.py --settings=settings_dev. The best way to make sure these environment variables are properly set is to append the export statement to your virtualenv's activate script. You are using virtualenv, right?

@jordanorelli
Copy link
Author

Oh and just as an aside, yes, this is really ugly, especially with the way the imports are scattered about, but I recommend putting any additional imports below this script, as some of the core django imports do some metaprogramming at import time that won't work unless it's imported after the execution of setup_environ.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment