29

I can move to a python project directory (say c:\www\myproject) and then issue

   python manage.py shell

and then I can use all modules from django project, say the following piece of commands from the shell command:

import settings 
from django.template import Template, Context

t=Template("My name is {myname}.")
c=Context({"myname":"John"})
f = open('write_test.txt', 'w')
f.write(t.render(c))
f.close

now, when I tried to collect all my commands into a python script, say "mytest.py", I cannot execute the script. I must missed something important.

I issued python mytest.py

then I got Import error: could not import settings Is it on sys path?"

I'm in the project directory where settings.py resides.....

Could some one help me out?

thanks.

Marcus Whybrow
  • 19,578
  • 9
  • 70
  • 90
john
  • 2,572
  • 11
  • 35
  • 51
  • Can you post the error? You most likely have a PYTHONPATH problem. Since your question mentioned the C: drive, I assume you are on Windows. http://docs.python.org/using/windows.html – dicato Jan 31 '11 at 03:55
  • Possible duplicate of [Django script to access model objects without using manage.py shell](http://stackoverflow.com/questions/8047204/django-script-to-access-model-objects-without-using-manage-py-shell) – Ciro Santilli OurBigBook.com May 13 '16 at 15:33

8 Answers8

23

Try using a Django management command instead.

# myproject/myapp/management/commands/my_command.py

from django.core.management.base import NoArgsCommand
from django.template import Template, Context
from django.conf import settings

class Command(NoArgsCommand):
    def handle_noargs(self, **options):
        t=Template("My name is {myname}.")
        c=Context({"myname":"John"})
        f = open('write_test.txt', 'w')
        f.write(t.render(c))
        f.close

And then (if you follow the docs) you will be able to execute the command in the following fashion:

python manage.py my_command
Marcus Whybrow
  • 19,578
  • 9
  • 70
  • 90
  • See my other answer, that might just do the trick. However if you want a tidy place for your scripts, then management commands might be the way to go. – Marcus Whybrow Jan 31 '11 at 04:05
23

This method is deprecated in Django 1.4. Use django.conf.settings.configure() instead (see @adiew's answer for example code).

Old method follows.

Put this at the beginning of your script

from django.core.management import setup_environ
import settings
setup_environ(settings)

This is really what the manage.py does behind the scene. To see it view the Django source in django/core/management/__init__.py. After executing these lines everything should be just like in ./manage.py shell.

phunehehe
  • 8,618
  • 7
  • 49
  • 79
  • 3
    This has been depreciated in Django 1.4. use @adieu instead `from django.conf import settings;settings.configure()` – saul.shanabrook Jul 24 '12 at 16:05
  • For me, this is the __right__ answer, still (as of Django 1.5 for me). `settings.configure()` is sometimes not enough – lajarre Nov 06 '13 at 22:03
11

Try put these two lines at the beginning of your script:

from django.conf import settings
settings.configure() # check django source for more detail

# now you can import other django modules
from django.template import Template, Context
adieu
  • 714
  • 3
  • 12
5

UPDATE: From another post.

./manage.py shell < myscript.py

Community
  • 1
  • 1
Babu
  • 2,548
  • 3
  • 30
  • 47
2

Instead of manually adding things to your python script, or having to fit in the management command format, in case this is not something that needs to stay around long, you can get all the benefits of the Django environment by running your script with ./manage.py runscript <myscript.py>

... but if your script is in your project folder, then you can just add this line to the top of the python script: import os; os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

James Sullivan
  • 101
  • 1
  • 7
  • 1
    Using runscript is a bit more complicated, but nicely summarized [here](http://blog.brendel.com/2012/01/how-to-use-djangextensions-runscript.html) – chrisst Sep 09 '14 at 06:40
2

To import Django's settings use:

from django.conf import settings
Marcus Whybrow
  • 19,578
  • 9
  • 70
  • 90
  • i put "from django.conf import settings" as the first line of my script, but still python cannot import settings.....am I using it the right way? thanks! – john Jan 31 '11 at 04:09
  • The reason I use management commands is because Django puts a bunch of stuff on the Python path when it starts up (such as `django`) and using a management command harnesses this. `python manage.py shell` starts up a regular version of the `python` interrupter but with the added environment. For example try executing your statements in the regular python interrupter rather than the django shell. – Marcus Whybrow Jan 31 '11 at 04:16
1

Saw in https://stackoverflow.com/a/24456404/4200284 a good solution for Django >= 1.7 and in case someone uses django-configurations this worked for me:

import sys, os, django

sys.path.append('/path/to/project')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.local") # path to config

## if using django-configurations
os.environ.setdefault("DJANGO_CONFIGURATION", "Local")
from configurations import importer
importer.install()

django.setup() ## apparently important for django 1.7

from foo.models import Bar

print Bar.objects.all()
Community
  • 1
  • 1
eule
  • 571
  • 6
  • 9
0

Here is yet another variant: I wrote and often use a management command "run" which has the advantage that scripts can see their command-line parameters:

http://lino-framework.org/api/lino.management.commands.run.html

Luc Saffre
  • 96
  • 2