用于运行 Django 命令的 Python 脚本
我想运行一个 python 脚本,它应该执行以下操作:
- 创建一个 django 项目:
django-admin startproject foobar
- 在项目中创建一个应用程序:
python manage.py barfoo
- 添加一个条目设置的
INSTALLED_APP
中新创建的应用barfoo
的名称。
我怎样才能实现这个目标?
I want to run a python scripts which should do:
- Create a django project:
django-admin startproject foobar
- Create a app in the project:
python manage.py barfoo
- Add an entry of newly created app
barfoo
in the setting'sINSTALLED_APP
.
How can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
似乎有一种Python式的方法可以做到#1和#2
https://docs.djangoproject.com/en/dev/ref/django-admin/#running-management-commands-from-your-code
There seems to be a pythonic way to do #1 and #2
https://docs.djangoproject.com/en/dev/ref/django-admin/#running-management-commands-from-your-code
6 年后,我偶然发现了这个问题,试图弄清楚如何为应用程序编写一些测试,该应用程序仅添加与项目中其他应用程序交互的自定义模板标签。希望这可以帮助别人。
基于 @groovehunter 答案:
请注意,在调用
startapp
之前,您需要将当前目录更改为创建的项目。有关更多详细信息,请参阅此答案,或者您可以使用
startproject
的附加参数来创建项目在当前目录下,如果确定不会有问题的话:6 years later I stumbled upon this question trying to figure out how to write some tests for an app which only add a custom template tag that interact with other apps in the project. Hope this can help someone.
Building on @groovehunter answer: the official documentation now (Django 1.10) inculdes this feature outside dev.
Note that you need to change current directory to the created project before call
startapp
. See this answer for more detailsor you can use the additional argumento to
startproject
to create the project in the current directory, if you're sure there won't be problems:阅读一些有关 subprocess 和 Popen 方法的内容。这可能就是您正在寻找的。
Popen(["django-admin", "startproject", "%s" % your_name ], stdout=PIPE).communicate()
Popen(["python", "manage.py", "%s" % your_app_name ], stdout=PIPE).communicate()
3.
我知道这不是一个完美的代码,但我只是提供一个想法。
Read a little abour subprocess and Popen method. This might be what you're looking for.
Popen(["django-admin", "startproject", "%s" % your_name ], stdout=PIPE).communicate()
Popen(["python", "manage.py", "%s" % your_app_name ], stdout=PIPE).communicate()
3.
I know that's not a perfect code, but I'm just giving an idea.