python / beginner
Snippet
Writing Custom Management Commands
Management commands allow you to create custom scripts that can be executed via 'python manage.py command_name'.
snippet.py
1
2
3
4
5
6
7
from django.core.management.base import BaseCommandclass Command(BaseCommand):help = 'Displays a simple greeting'def handle(self, *args, **options):self.stdout.write('Hello from the CLI!')
django
Breakdown
1
class Command(BaseCommand):
Django looks for a class named 'Command' inside 'management/commands/' files.
2
def handle(self, *args, **options):
The main entry point where your command's logic resides.
3
self.stdout.write(...)
The standard way to print output to the console in a Django command.