Skip to content

Q&A · Answered

How to create custom Django management commands

asked 9 months, 1 week ago 1266 views 1 answer
12

I need to create a custom command that I can run with manage.py. How do I create one?

1 Answer

One accepted
10

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago

Create command file structure

myapp/
    management/
        __init__.py
        commands/
            __init__.py
            mycommand.py

Write the command

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

class Command(BaseCommand):
    help = 'Description of my command'

    def add_arguments(self, parser):
        parser.add_argument('--name', type=str)

    def handle(self, *args, **options):
        name = options.get('name', 'World')
        self.stdout.write(f'Hello, {name}!')
        self.stdout.write(self.style.SUCCESS('Done!'))

Run the command

python manage.py mycommand --name John

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.