Scheduling Custom Django Management Commands
Last updated 13 May 2020
Create a custom management command
Create the Python file
Custom Django management commands are nested within a Django project’s apps. For this tutorial, if the Django project contains more than one app, decide which app the custom management command will most closely relate to, and use that app to follow the steps below.
A Django project contains one or more apps. In this tutorial, you’ll be working within one of the apps and not the overall Django project.
The Python file that contains the code for the custom command is nested inside several directories:
- At the root level of the Django app, create a directory called
commandscreate a file named something similar to
print_book_titles.py. Stylistically, the name you choose for this file should reference the outcome of the task when it runs.
At this stage, the app’s file tree will look similar to this:
some_app/ __init__.py models.py management/ commands/ print_book_titles.py tests.py views.py
Django automatically maps the name of the command file to the command that is run in the CLI (
python manage.py print_book_titles)
Code the command’s logic
The following code snippet is for a short custom management command. View the Django documentation on Writing custom django-admin commands for guidance on more complex needs.
from django.core.management.base import BaseCommand, CommandError from some_app.models import Book class Command(BaseCommand): help = 'Prints all book titles in the database' def handle(self): try: books = Book.objects.all() for book in books: self.stdout.write(self.style.SUCCESS(book.title)) except FieldDoesNotExist: self.stdout.write(self.style.ERROR('Field "title" does not exist.')) return self.stdout.write(self.style.SUCCESS('Successfully printed all Book titles')) return
return statement at the end of each logical flow of the
handle() function so Heroku Scheduler knows when it can shut down. This ensures you are only charged for dyno time that is needed to run the job.
Verify the command works as expected
Ensure the command works by running it in a one-off dyno:
- From the CLI, run
heroku run bash -a your-app-name
- Navigate to the directory containing
python manage.py <your_custom_command>
Setup Heroku Scheduler
Provision the Add-on
Schedule the job
Open the Heroku Scheduler tool by following the steps in Heroku Scheduler - Scheduling Jobs. When prompted, enter
python manage.py <your_custom_command> as the command to run.
manage.py file is not at the root level of the Heroku app’s git repo, the command that is run within Heroku Scheduler will need to first navigate to the directory that contains the
manage.py file. The command would look something like
cd my-project && python manage.py <your-command-name>.