我想运行一个应该执行的python脚本:
django-admin startproject foobar
python manage.py barfoo
barfoo
中添加新创建的应用INSTALLED_APP
的条目。我怎样才能做到这一点?
答案 0 :(得分:10)
似乎有一种pythonic方式来做#1和#2
https://docs.djangoproject.com/en/dev/ref/django-admin/#running-management-commands-from-your-code
from django.core import management
management.call_command('flush', verbosity=0, interactive=False)
management.call_command('loaddata', 'test_data', verbosity=0)
答案 1 :(得分:2)
阅读一些abour子进程和Popen方法。这可能就是你要找的东西。
Popen(["django-admin", "startproject", "%s" % your_name ], stdout=PIPE).communicate()
Popen(["python", "manage.py", "%s" % your_app_name ], stdout=PIPE).communicate()
3。 我知道这不是一个完美的代码,但我只是在提出一个想法。
with open("settings.py", 'r') as file:
settings = file.readlines()
new_settings = []
for line in settings:
if "INSTALLED APPS" in line:
new_settings.append(line.replace("INSTALLED_APPS = (", "INSTALLED_APPS = (\n'%s'," % your_app_name))
else:
new_settings.append(line)
with open("settings.py", 'w') as file:
file.write("".join(new_settings))
答案 2 :(得分:1)
在@groovehunter的基础上回答:official documentation现在(Django 1.10)在dev之外加入了这个功能。
请注意,在调用startapp
之前,您需要将当前目录更改为已创建的项目。有关详细信息,请参阅this answer
from django.core import management
import os
management.call_command('startproject', 'foobar')
os.chdir('foobar')
management.call_command('startapp', 'barfoo')
或者您可以使用附加参数来startproject
在当前目录中创建项目,如果您确定不会出现问题:
from django.core import management
management.call_command('startproject', 'foobar', '.')
management.call_command('startapp', 'barfoo')