Extending Django Commands

If you’ve ever wanted to “do something every X minutes” with Django, there are two options that I have found:

  1. Use a Django plugin that will create cronjobs for you
  2. Create custom commands and create your own cronjobs

This short guide is for the second option since this seems to be the best way to do things (for me at least).

There are more reasons to create custom commands besides cron. You could, for instance, create a setup command that will insert some data into a database for initialization purposes, or perhaps add a user to a database.

  1. Create the commands folder.

    mkdir -p PROJECT/management/commands

    Obviously, replace PROJECT with your project folder name.

  2. Create a file in that folder. The file name will become your command name.

  3. Create a class inside the file.

from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):

	def handle(self, *args, **options):
		# Do something
  1. Create a cronjob that will execute python3 manage.py COMMAND (replace command with the file name you created above).

Here are a few crontab generators if you need them: