1

I want to run a python scripts which should do:

  1. Create a django project: django-admin startproject foobar
  2. Create a app in the project: python manage.py barfoo
  3. Add an entry of newly created app barfoo in the setting's INSTALLED_APP.

How can I achieve this?

groovehunter
  • 3,050
  • 7
  • 26
  • 38
g_inherit
  • 18,771
  • 3
  • 16
  • 5

3 Answers3

12

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)
groovehunter
  • 3,050
  • 7
  • 26
  • 38
4

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')
Community
  • 1
  • 1
Antiphon0x
  • 197
  • 1
  • 10
2

Read a little abour subprocess and Popen method. This might be what you're looking for.

  1. Popen(["django-admin", "startproject", "%s" % your_name ], stdout=PIPE).communicate()

  2. 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))
agf
  • 171,228
  • 44
  • 289
  • 238
Gandi
  • 3,522
  • 2
  • 21
  • 31