How to create management commands in Django

  • By PyCat
  • Apr 26, 2017
  • Django Practices

[Photo from Unsplash]


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 makemigrations or migrate commands in your projects.

So these commands, also called as management commands are used to execute some piece of code from command line. You can read more in the Django Framework Documentation for management commands.In this article we will describe how to create our own commands.

Why do you need management command:

First thing that comes to your mind a is that why do even I need management command in our project. 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.

How to create a management command:

Follow below steps to create your own management command.

  •     Create a directory in your application and name it management .
  •     Create a blank  __init__.py  file inside it.
  •     Create a directory named as commands  inside management  directory.
  •     Create a blank __init__.py  file inside commands  directory.
example in myapp
|-management
|    |-commands
     |   |-__init__.py
     |   |-mycommand.py
     |-__init__.py

Inside commands  directory create a file with name of your command. Lets say firstcommand.py.
The code for your command should look like this
 

class Command(BaseCommand): 
   help = 'Descrives the commands purpose.. what it does'

   def add_argument(self, parser):
   # Here we can set any arguments we might need when we run the command, eg parser.add_argument('user_id', nargs='+', type=int)

   def handle(self, *args, **options): 
      try: # our logic here
          print("I Hello World") pass
      except Exception as e: CommandError(repr(e))

      self.stdout.write(self.style.SUCCESS('Successfully did what it had to do'))

 

First we need to  define a class with name Command  which extends BaseCommand .

Then If we want to add any arguments to our command from the command line we can use the add_argument  function.

Then comes the commands logic. Write whatever logic you want to execute in handle function (you can query the database, just get the infrormation or even update it etc etc).

Last step is to seve our command file  execute the command on terminal, passing arguments if there are any. You will see the output on the screen.

$ python manage.py mycommand 

We can run our commands manually or  in crontab to execute it periodically.


Find me

kabardi.cat@gmail.com