Extending Django Commands
Nov 10, 2015
If you’ve ever wanted to “do something every X minutes” with Django, there are two options that I have found:
- Use a Django plugin that will create cronjobs for you
- 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.
-
Create the commands folder.
mkdir -p PROJECT/management/commands
Obviously, replace
PROJECT
with your project folder name. -
Create a file in that folder. The file name will become your command name.
-
Create a class inside the file.
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
def handle(self, *args, **options):
# Do something
- 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: