简体   繁体   中英

Python script to run Django commands

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?

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)

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))

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM