Blog available for sell
This blog is available for sale. Please 'contact us' if interested.
Advertise with us
commands   0   13419
How to create management commands in Django

You must have used createsuperuser command in your Django application at one or another 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 the command line.

In this article, We will see how to create your own command.



Why do you need management command:

The first thing that comes to your mind after reading the above paragraph is why do even I need management command in my project.

Let's say you have a project where you need to perform some tasks periodically.

For example, updating the database column after fetching data from some other server, sending lots of emails, taking the backup of your database, etc, etc.



How to create a management command:

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

myapp
 |-management
 |    |-commands
      |   |-__init__.py
      |   |-mycommand.py
      |-__init__.py


- Inside commands directory create a file with the name of your command. Let's say mycommand.py.
- 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))


 - We must define a class with the name Command which extends BaseCommand.
 - Here add_argument function is used to add the arguments to command on the 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.

$ python manage.py mycommand
   


Positional Arguments:

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

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

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



Code on Github:

Please use this GitHub link to download the sample code for this article.


commands   0   13419
0 comments on 'How To Create Management Commands In Django'
Login to comment


Related Articles:
Django-Admin commands cheat sheet
A complete list of Django-Admin commands with a brief description, Django-admin commands list, Cheatsheet Django Admin commands,...
How to schedule a cron on pythonanywhere server
Scheduling task on pythonanywhere server. Step by step process to add cron task on pythonanywhere server free account. Django command scheduling....
DigitalOcean Referral Badge

© 2024-2025 Python Circle   Contact   Sponsor   Archive   Sitemap