Snippet to load stuff quickly in the Django shell

Sometimes you end up testing out things a lot using the handy django shell, but every time you’ve got to repeat the same commands to load all the necessary models, utils etc. etc.

Picture 1

In order to do this automatically, I thought you had to modify the django-admin.py file or something like that. Nope! Here’s a useful django snippet that shows how to do the job. Basically – it’s very simple (I actually don’t understand how I got stuck on something so obvious!), just put evetyhing you want to load  in a separate file in your project, and then load that file from the shell ;-)

E.g..

'''
Allows for a quick startup loading commonly used classes, installed apps, and console utils.

To use: After manage.py shell, enter from project.package.modulename import *
'''

from django.conf import settings
from django.db import connection, models

# Load each installed app and put models into the global namespace.
for app in models.get_apps():
    exec("from %s import *" % app.__name__)

def last_query():
    "Show the last query performed."
    return connection.queries[-1]

#===================================================
# Add commonly used modules, classes, functions here
#===================================================
from django import forms
import os
from datetime import datetime

# etc. etc.

p.s.
also snippets 540 and 549 provide alternative solutions to the problem!

 

Share/Bookmark






3 Responses to “Snippet to load stuff quickly in the Django shell”

There is something missing from the instructions, I think.

Put the above code into a file at your doc root, call it libloader.py, for example.

Then:

>python manage.py shell

>>>execfile(“./libloader.py”)

Joel Bremson added these pithy words on Sep 03 09 at 4:19 am

yeah you can do it that way, although I usually keep it in my project folder in a package containing other utilities, and then load it with this:
>>> from myproject.mytools.libloader import *

magicrebirth added these pithy words on Sep 11 09 at 1:24 pm

Thanks for this post. I am new at development and this is a big help.

Gregory Despain added these pithy words on Mar 06 10 at 9:07 pm