Skip to content

Django Custom Commands

We can create our own custom management commands in Django to automate tasks and add new functionality that we can run from the command line. Custom commands are handy when you want to run scripts, do maintenance tasks, or run any other piece of code straight from your terminal.

To create a custom command, follow these steps:

  1. Create a management/commands folder inside one of your Django apps. For example, if your app is called myapp, your folder structure should look like this:
myapp/
management/
commands/
__init__.py
my_command.py
  1. Inside the my_command.py file, create a class that inherits from BaseCommand, and add a handle method inside it. The handle method is where you write the actual code that should run when someone runs your command.
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Description of what the command does'
def handle(self, *args, **kwargs):
# Your code here
self.stdout.write('Command executed successfully!')
  1. You can run your custom command using the manage.py script. For example, if your command is named my_command, just type this in your terminal:
Terminal window
uv run python manage.py my_command

Custom commands let you automate repetitive tasks, handle maintenance work, and add new features to your Django app, all without needing to write separate standalone scripts. They fit nicely into your everyday workflow, and since you can run them straight from the command line, they’re a really handy tool to have as a developer.

  • Use the help attribute to write a short description of what your command does. This helps other developers understand what the command is for when they run python manage.py help.
  • Use self.stdout.write() to print messages to the console. This is the recommended way to show output from your command, since it works nicely with Django’s formatting and logging system.
  • You can also use self.stderr.write() to print error messages to the console.
  • If your command needs to take in arguments or options, you can set them up using the add_arguments method. This lets you build commands that are more flexible and powerful.
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Description of what the command does'
def add_arguments(self, parser):
parser.add_argument('arg1', type=str, help='Description of arg1')
parser.add_argument('--option1', type=str, help='Description of option1')
def handle(self, *args, **kwargs):
arg1 = kwargs['arg1']
option1 = kwargs.get('option1')
# Your code here
self.stdout.write(f'Command executed with arg1: {arg1} and option1: {option1}')