Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use django: from "python manage.py shell" to python script

Tags:

python

django

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.

like image 366
john Avatar asked Jan 31 '11 03:01

john


People also ask

What is the use of python manage py shell command in Django project?

In addition, manage.py is automatically created in each Django project. It does the same thing as django-admin but also sets the DJANGO_SETTINGS_MODULE environment variable so that it points to your project's settings.py file.


2 Answers

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 
like image 197
Marcus Whybrow Avatar answered Oct 14 '22 06:10

Marcus Whybrow


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.

like image 23
phunehehe Avatar answered Oct 14 '22 05:10

phunehehe