You must have used
createsuperuser command in your Django application at one or other time. If not then I am sure you must have used
migrate commands in your project. Yes? Yes.
So these commands, also called as management commands are used to execute some piece of code from command line.
In this article I will tell you how to create your own command.
Lets say you have a project where you need to perform some task periodically.
For example: updating database column after fetching data from some other server, sending lots of mails, taking backup of your database etc etc.
- Create a directory in your application and name it management .
- Create a blank
__init__.py file inside it.
- Create a directory named as
- Create a blank
__init__.py file inside commands directory.
myapp |-management | |-commands | |-__init__.py | |-mycommand.py |-__init__.py
commands directory create a file with name of your command. Lets say
- Add below code to this file.
from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = 'Command to do........' def add_argument(self, parser): pass def handle(self, *args, **options): try: # your logic here print("I am here") except Exception as e: CommandError(repr(e))
add_argumentfunction is used to add the arguments to command on command line.
$ python manage.py mycommand
def add_arguments(self, parser): parser.add_argument('msg', nargs='+', type=str)
Now you may use this variable
msg in your command.
def handle(self, *args, **options): try: # your logic here msg = options["msg"] print(msg) print("I am here") except Exception as e: CommandError(repr(e))
You can use this command in crontab to execute is periodically.