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?

3 Answers 3

13

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)
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')
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))
1
  • Maybe for #1, but not for #2 or #3. Those are both easily doable in Python.
    – agf
    Aug 18, 2011 at 12:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.