Skip to content Skip to sidebar Skip to footer

Running A Standalone Script Doing A Model Query In Django With `settings/dev.py` Instead Of `settings.py`

Note the settings/dev.py instead of one settings.py file and the script.py in my_app in the following Django(1.4.3) project: . ├── my_project │ ├── my_app │ │

Solution 1:

If you're looking to just run a script in the django environment, then the simplest way to accomplish this is to create a ./manage.py subcommand, like this

from django.core.management.base import BaseCommand
from my_app.models import MyModel

class Command(BaseCommand):
    help = 'runs your code in the django environment'

    def handle(self, *args, **options):
        all_entries = MyModel.objects.all()
        for entry in all_entries:
            self.stdout.write('entry "%s"' % entry)

The docs are quite helpful with explaining this.

However, you can specify a settings file to run with using

$ django-admin.py runserver --settings=settings.dev

which will run the test server using the settings in dev however, I fear your problems are more deep seated than simply that. I wouldn't recommend ever changing the manage.py file as this can lead to inconsistencies and future headaches.

Note also that dev.py should be a complete settings file if you are to do this. I would personally recommend a structure like this:

|-settings
|    |- __init__.py
|    |- base.py
|    |- dev.py
|    |- prod.py

and keep all the general settings in your base.py and change the first line of your dev.py etc to something like

# settings/dev.py
from .base import *

DEBUG = True
...

EDIT

If you're just looking to test things out, why not try

$ ./manage.py shell

or with your dev settings

$ django-admin.py shell --settings=settings.dev

as this will set all the OS environment variables, settings.py for you, and then you can test / debug with

>>> from my_app.models import MyModel
>>> all_entries = MyModel.objects.all()
>>> for entry in all_entries:
...   print entry    

Post a Comment for "Running A Standalone Script Doing A Model Query In Django With `settings/dev.py` Instead Of `settings.py`"