Reputation: 20331
I want to run a python scripts which should do:
django-admin startproject foobar
python manage.py barfoo
barfoo
in the setting's INSTALLED_APP
.How can I achieve this?
Upvotes: 1
Views: 5429
Reputation: 327
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 details
from django.core import management
import os
management.call_command('startproject', 'foobar')
os.chdir('foobar')
management.call_command('startapp', 'barfoo')
or 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:
from django.core import management
management.call_command('startproject', 'foobar', '.')
management.call_command('startapp', 'barfoo')
Upvotes: 4
Reputation: 3158
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
from django.core import management
management.call_command('flush', verbosity=0, interactive=False)
management.call_command('loaddata', 'test_data', verbosity=0)
Upvotes: 13
Reputation: 3652
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.
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))
Upvotes: 2