在Django中:从"python manage.py shell"到Python脚本

30 投票
8 回答
56099 浏览
提问于 2025-04-16 10:55

我可以进入一个Python项目的目录(比如 c:\www\myproject),然后执行

   python manage.py shell

接着我可以使用Django项目中的所有模块,比如在命令行中输入以下命令:

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

现在,当我尝试把所有命令放到一个Python脚本里,比如叫“mytest.py”,我却无法执行这个脚本。我一定是漏掉了什么重要的东西。

我输入了 python mytest.py

然后我得到了 Import error: could not import settings 这个错误,问我“它在sys路径上吗?”

我在settings.py文件所在的项目目录里……

有人能帮我一下吗?

谢谢。

8 个回答

11

试着把这两行代码放在你脚本的开头:

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
23

这个方法在Django 1.4中已经不推荐使用了。建议用 django.conf.settings.configure() 来代替(可以参考@adiew的回答中的示例代码)。

下面是旧的方法。

把这段代码放在你脚本的开头

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

其实这就是manage.py在后台做的事情。如果想看看具体内容,可以查看Django的源代码,路径是 django/core/management/__init__.py。执行完这些代码后,所有的东西就和在 ./manage.py shell 中一样了。

23

试试用一个 Django 管理命令 来解决这个问题。

# 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

然后(如果你按照文档的说明操作),你就可以用以下方式来执行这个命令:

python manage.py my_command

撰写回答