Skip to content

Django Custom Commands

We can create custom management commands in Django to automate tasks and extend the functionality of the Django admin. Custom commands are useful for running scripts, performing maintenance tasks, or any other functionality that you want to execute from the command line.

To create a custom command, you need to follow these steps:

  1. Create a management/commands directory inside one of your Django apps. For example, if you have an app called myapp, you would create the following directory structure
management/
commands/
__init__.py
my_command.py
  1. Inside the my_command.py file, you need to define a class that inherits from BaseCommand and implement the handle method. The handle method is where you will write the code that you want to execute when the command is run.
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 called my_command, you would run the following command in your terminal:
Terminal window
uv run python manage.py my_command

Custom commands allow you to automate repetitive tasks, perform maintenance, and extend the functionality of your Django application without having to write separate scripts. They can be easily integrated into your development workflow and can be run from the command line, making them a powerful tool for developers.

  • Use the help attribute to provide a description of what the command does. This will help other developers understand the purpose of the command when they run python manage.py help.
  • Use self.stdout.write() to print messages to the console. This is the recommended way to output information from your command, as it allows for better formatting and integration with Django’s logging system.
  • You can also use self.stderr.write() to print error messages to the console.
  • If your command takes arguments or options, you can define them using the add_arguments method. This allows you to create more flexible and powerful commands.
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}')