Field Notes

Quick How-To : Custom Django Management Commands

November 27, 2014 | In python

Django's 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
    | | |--
    | | `-- commands
    | | |--
    | | `

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

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

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

$ touch management/
    $ touch management/commands/

Forgetting to add will cause an error like this:

$ python allTheThings
    Unknown command: 'allTheThings'

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

    $ emacs

4) Here are the essential parts of a command:

    from 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 doAllTheThings

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