Janet Riley

Quick How-To : Custom Django Management Commands

November 27, 2014 | In python

Django's manage.py runs a variety of Django admin tasks. We can add custom tasks as well. This is useful for running commands through a shell script, as with a cron job.

Say you have a package called myPackage. Let's add a custom command called doAllTheThings . This example uses Python 2.7.6 and Django 1.7 .

Here's a preview of the files we'll create.

$ tree
    .
    |-- myPackage
    | |-- management
    | | |-- __init__.py
    | | `-- commands
    | | |-- __init__.py
    | | `--allTheThings.py

0) Add your package to INSTALLED_APPS in settings.py if it isn't there already.

1) In your package directory, create management and management/commands subdirectories. The names matter.

2) Create __init__.py files in both to signal that these are packages. ( This may be different in Python 3.)

$ touch management/__init__.py
    $ touch management/commands/__init__.py

Forgetting to add __init__.py will cause an error like this:

$ python manage.py allTheThings
    Unknown command: 'allTheThings'

3) Create a python file with the same name as your command.

    $ emacs allTheThings.py

4) Here are the essential parts of a command:

    from django.core.management import BaseCommand

    #The class must be named Command, and subclass BaseCommand
    class Command(BaseCommand):
    # Show this when the user types help
    help = "My test command"

    # A command must define handle()
    def handle(self, *args, **options):
    self.stdout.write("Doing All The Things!")

5) Run the command like any other Django management command. From the top directory in your Django project,

$ python manage.py doAllTheThings

For more detail, including how to parse arguments, see the Django developer guide