How to create management commands in Django

creating management commands in django

 

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 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.

Why do you need management command:

First thing that comes to your mind after reading above paragraph is that why do even I need management command in my 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.

– Inside commands  directory create a file with name of your command. Lets say mycommand.py.

– Add below code to this file.

– We must define a class with name Command  which extends BaseCommand .

– Here add_argument  function is used to add the arguments to command on command line.

– Write whatever login you want to execute in handle function. Pro tip here : If your logic is very lengthy, you can write it as a separate service and call that service function in your handle function.

–  Save the files and on terminal execute your command. You will see the output on the screen.

 

 

Positional Arguments:

You may pass and accept the command line positional arguments to your command.

Now you may use this variable msg  in your command.

 

You can use this command in crontab to execute is periodically.

Read this article on how to schedule a task on pythonanywhere.com server.

 

Code on Github:

Please use this github link to download sample code for this article.
Github URL : https://github.com/anuragrana/django-command.git

Video:

You can watch this short video on how to create management command in django.

 

 

(Visited 1,273 times, 1 visits today)

You must read this :

2 thoughts on “How to create management commands in Django”

Leave a Reply

Your email address will not be published. Required fields are marked *