This post is the seventh and last in a series on Django tricks that began with automating Admin Model creation.
This is one of my favorite tricks: setup the Django environment from the Python interpreter.
(master) $ python >>> from lib.django_from_shell import start_django as sd >>> sd() >>> from procrasdonate.models import User >>> User.objects.count() 22
All we need to do is wrap a few Django calls like so:
def start_django(): import sys #Now the nearest ancestor directory with a 'settings.py' file settings_dir = find_file_in_ancestors("settings.py") sys.path.append(settings_dir) from django.core.management import setup_environ import settings setup_environ(settings)
By being flexible about finding the global settings.py file, we can call start_django from other scripts buried in bin or cron directories:
def find_file_in_ancestors(filename): """ For each parent directory, check if 'filename' exists. If found, return the path; otherwise raise RuntimeError. """ import os path = os.path.realpath(os.path.curdir) while not filename in os.listdir(path): #if filename in os.listdir(path): # return path newpath = os.path.split(path)[0] if path == newpath: raise RuntimeError("No file '%s' found in ancestor directories." % filename) path = newpath return path
Conclusion
The goal of these tricks is to reduce copy/past/alter drudgery. It’s rewarding to automate the creation of fluff code, even easy fluff that knocked my socks off when I first learned Django.
Of course, it’s hard to stay impressed with myself or Dan for long since I quickly forget that the fluff code even existed. I suppose that’s part of the point. I can forget about creating Admin Models, and new models still show up in the Admin app as I thoughtlessly expected.
Still, even if I’m not impressed, I do notice how often I get to write new, interesting code. That’s why I’m Proudly ProcrasDonating,
Lucy.








