Custom Management Command

A snippet showing how to build custom Django management commands.


# myapp/management/commands/hello.py
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = 'Prints a greeting message'

    def add_arguments(self, parser):
        parser.add_argument('name', type=str, help='Name to greet')

    def handle(self, *args, **options):
        name = options['name']
        self.stdout.write(self.style.SUCCESS(f'Hello, {name}!'))
  
Explanation:
  • Create app/management/commands/ directory with __init__.py files.
  • Subclass BaseCommand and implement handle() method.
  • Run with python manage.py hello <name>.
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.