tags:

views:

609

answers:

3

I have a script which uses the Django ORM features, amongst other external libraries, that I want to run outside of Django (that is, executed from the command-line).

Edit: At the moment, I can launch it by navigating to a URL...

How do I setup the environment for this?

+5  A: 
from <Project path>          import settings          #your project settings file
from django.core.management  import setup_environment

setup_environ(settings)

#Rest of your django imports and code go here
Fausto I.
Unfortunately this method does not work if you use a script in \app1\ and need to use files from \app2\ unless you place it in the project root.
Mark Stahler
I think it should be "import setup_environ" instead of "import setup_environment"
del
+3  A: 

All you need is importable settings and properly set python path. In the most raw form this can be done by setting up appropriate environment variables, like:

$ DJANGO_SETTINGS_MODULE=myproject.settings PYTHONPATH=$HOME/djangoprojects python myscript.py

There are other ways, like calling settings.configure() and already mentioned setup_environ() described by James Bennett in some blog post.

zgoda
+1: Do this all the time. We have many batch jobs that use the ORM.
S.Lott
+7  A: 

The easiest way to do this is to set up your script as a manage.py subcommand. It's quite easy to do:

from django.core.management.base import NoArgsCommand

class Command(NoArgsCommand):

    help = "Whatever you want to print here"

    option_list = NoArgsCommand.option_list + (
        make_option('--verbose', action='store_true'),
    )

    def handle_noargs(self, **options):
        ... call your script here ...

Put this in a file, in any of your apps under management/commands/yourcommand.py (with empty __init__.py files in each) and now you can call your script with ./manage.py yourcommand.

Daniel Roseman
This is the option that I use, assuming the command is related to your project.
Daveyjoe