Jeez, why is this so hard to find info on?

You know the deal, you have your fantastic Django application and it’s working great and everything, but you need to make a small change which is too cumbersome to do in the shell, so you figure “duh, I’ll just write a script to do it”. You write your external script in two minutes and then struggle for two hours to figure out how to load the models and the rest of the context so it will work with your app’s settings and all your Django goodness.

You visit StackOverflow and a bunch more sites, and they either tell you to use a management command, which is great advice, except your thing is a one-off and you don’t want to have to check it to git and go through all that hassle to get it deployed just to do this simple thing, or they give you some arcane lines that just don’t work.

Fear not, for I am here. I will give you five simple lines that will make everything work perfectly. Perfectly, I say!

Without further ado (all the previous ado was just so I could fill the paragraph so the side-box doesn’t look weird with short text), I give you the magic commands! Here they are:

import os, sys

proj_path = "/path/to/my/project/"
# This is so Django knows where to find stuff.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
sys.path.append(proj_path)

# This is so my local_settings.py gets loaded.
os.chdir(proj_path)

# This is so models get loaded.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

<your script goes here>

I hope this saves you an hour or something.

EDIT: My friend Josh points out that this is just wsgi.py, to which I reply “yeah thanks Josh, where were you two hours ago?”