Search Here

Learn Django Command Management, Create Custom Command

Learn Django Command Management, Create Custom Command

Django Framework is an idle web framework that contains all the toolset of a modern framework and in this post, you’ll Learn Django Command Management, Custom Command and become Pro in it.

Steps to create a Custom Command in Django

Follow the below steps to create a custom command in your Django Application.

  • Register your app in the settings.py file under INSTALLED_APPS.
  • All custom commands in Django exist in the management/commands/ folder within your app.
  • Within the commands folder, you’ll be adding files that will be considered as commands by the Django framework.

Example of Custom Command

To create a custom command you must import BaseCommand from from django.core.management.base import BaseCommand.
There are two methods that will be overriding and they are add_arguments and handle method.

In add_arguments we can specify both of the positional and named parameters that will be passed by the user while executing the command via the command line.
And handle a method that is mandatory will be implicitly called where parameters provided by users can be retrieved.

from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = 'Displays your name'

    def add_arguments(self, parser):
        parser.add_argument('name', nargs='+', type=int ) 

    def handle(self, *args, **options):
        name = options['name']
        self.stdout.write(self.style.SUCCESS(f'Your name is {name}'))

The above command will display the name you have provided in green font color.

The method self.stdout will display the output on the console. You can alternatively use self.stderr the method also.

The class attribute help describes the command and is displayed when you type python manage.py help your_command.

Display Output is different colors

You can display output messages in the terminal in four different font colors and they are SUCCESS, ERROR, WARNING and NOTICE.

The methods self.style.SUCCESS, self.style.ERROR etc will not display colored font in windows CMD terminal. But will work on modern terminals.

Adding Arguments to Command and Validation

The arguments can be added using add_argument method. The first parameter will be the positional parameters and the other parameters will be optional. The method must be called on a parser object which will be received as a parameter in add_arguments the method.
Example of a positional parameter.

parser.add_argument('name')

You can also specify the type of data the parameter holds by adding an argument type=int or type=str.

parser.add_argument('name', type=str)

You can also add a default value to the argument by adding default and providing value to it. But it works only for named arguments.

parser.add_argument('--name', default="Not Available" type=str)

You also specify the number of values the parameter can take by specifying nargs which is a number of arguments.
The values for nargs are defined below:

  • +:Takes more than one value but At least one value is required to be provided.
  • ?: Takes a single value but it is also optional.
  • *: Takes multiple values and creates a list. It is an optional parameter
  • n: This takes a number and the values must be exactly the same number as mentioned.
parser.add_argument('name', type=str, nargs=1)
parser.add_argument('hobbies', type=str, nargs='*')
parser.add_argument('courses', type=str, nargs='+')
parser.add_argument('phone_no', type=str, nargs='?')

Here is the documentation on Python argparser nargs.

Providing a Named Parameter to the argument

To make an argument as named you must use – dash or — double dash symbol before it. And these arguments are optional and contains None if a value is not passed.

parser.add_argument('--named', type=str)

You can also add an argument metavar to accept multiple values.

parser.add_argument('--named', type=str, metavar=('val1', 'val2'), nargs=2)

#In command line
#python manage.py command_name --named "Sumit" "Patil"
Also read all of our posts related to Django Framework

Raising Command Exceptions

There are always of having some errors in the command handle method and you can raise those exceptions using CommandError object.

raise CommandError("Something went wrong")

Create a Custom Command that displays Quotes

A simple example of getting random quotes when we enter a command python manage.py quotes.
In \management\commands\quotes.py

from django.core.management.base import BaseCommand, CommandError
import random

class Command(BaseCommand):
    help = 'Displays quotes'

    def handle(self, *args, **options):
        quotes = [ 
            "sample quote 1",
            "sample quote 2",
            "sample quote 3",
        ]
        quote = random.choice(quotes)
        self.stdout.write(self.style.SUCCESS(f'The Quote is \n {quote}'), ending='\n')
    

Calling Commands through code within Django Views

You can also execute commands through code within views. For that, you have to from django.core import management and to call command use call_command('command_name', 'parameter 1', 'parameter 2', 'parameter n').
In views.py

from django.shortcuts import render, HttpResponse
from django.core import management

# Create your views here.
def run_command_quotes( request ):
    management.call_command('quotes')
    return HttpResponse("ok")

Capture Django Custom Commands return value

There are two ways you can get return value from commands. The first is to use StringIO a class which will store the output string and then you can retrieve it by calling .getvalue() method.

from django.shortcuts import render, HttpResponse
from django.core import management
from io import StringIO

# Create your views here.
def run_command_quotes( request ):
    string_io=StringIO()
    management.call_command('quotes', stdout=string_io)
    value = string_io.getvalue()
    return HttpResponse(value)

The problem here is that the output value also contains some random symbols and characters and if you don’ want to have these characters in your output then the second method is to simply return the data from the command handle() method, then save in a variable and display on the screen.

def handle(self, *args, **options):
    quotes = [ 
        "sample quote 1",
        "sample quote 2",
        "sample quote 3",
    ]
    quote = random.choice(quotes)
    op = f'The Quote is \n {quote}'
    return op

Caution

The above code is not recommended as Django recommends to use self.stdout to display on the screen and also we don’t recommend using the above example as it is showing you various ways of getting data.

Watch Video

Conclusion

We have reached the end of this post on Creating Custom Commands in Django Framework.