📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Django Framework Django Custom Management Commands

Django Custom Management Commands

5 min read
Write management commands with BaseCommand, add_arguments(), and handle() for admin scripts.

Custom Management Commands

# blog/management/commands/send_digest.py
from django.core.management.base import BaseCommand
from django.utils import timezone

class Command(BaseCommand):
    help = "Send weekly email digest to subscribers"

    def add_arguments(self, parser):
        parser.add_argument("--dry-run", action="store_true", help="Simulate without sending")
        parser.add_argument("--limit", type=int, default=100, help="Max recipients")

    def handle(self, *args, **options):
        dry_run   = options["dry_run"]
        limit     = options["limit"]
        users     = User.objects.filter(subscribed=True)[:limit]
        posts     = Post.objects.filter(
            is_draft=False,
            created_at__gte=timezone.now() - timedelta(days=7)
        )

        for user in users:
            if not dry_run:
                send_digest_email(user, posts)
            self.stdout.write("Sent to " + user.email)

        self.stdout.write(self.style.SUCCESS("Done! Sent " + str(users.count()) + " emails."))

# python manage.py send_digest --dry-run --limit=10