Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
992 views
in Technique[技术] by (71.8m points)

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

I can move to a python project directory (say c:wwwmyproject) 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...