How to create a custom management command in
#Django? π οΈ
1οΈβ£ Organize your Django app directories and files as follows:
myapp/
β
βββ __init__.py
βββ
models.py
βββ
views.py
βββ management/
βββ commands/
βββ __init__.py
βββ my_command.py
2οΈβ£ Add your command class to management/commands/my_command.py:
Example code my_command.py in image below ...
-> This class defines what the command does, how it should be called, and how it handles its arguments.
3οΈβ£ Run the custom management command:
$ python
manage.py my_command --option=value
-> Now you can run your custom command just like you would run built-in Django management commands (like runserver, migrate, etc.).
These reusable Django command line scripts are very useful for database maintenance, system monitoring/ reporting, data importing/exporting, and other maintenance tasks. π©βπ»π
#python #webdevelopment #djangodevelopment #djangotips #pybobtips
ALT from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Description of the command'
def add_arguments(self, parser):
# Optional argument
parser.add_argument('--option', type=str, help='An optional argument')
def handle(self, *args, **kwargs):
option = kwargs['option']
self.stdout.write(self.style.SUCCESS('Starting command...'))
# Your command logic here
...
self.stdout.write(self.style.SUCCESS('Command completed successfully!'))