Created
June 14, 2011 17:40
-
-
Save jordanorelli/1025419 to your computer and use it in GitHub Desktop.
Load Django environment for CLI script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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. |
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
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 optionalDJANGO_SETTINGS_MODULE
variable that, if present, will be used as the settings module. E.g., runningexport 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?