Django Management Commands

Published on

Django admin commands are one of the powerful features provides ways to add command line utility functionalities to our application. Django provides many built in commands for various options. Some of most commonly used commands are

  • runserver - to run development server of the application
  • createsuperuser - to create super user of the application
  • shell - to open python interactive shell and with ability use Django apps
  • migrate - to Apply migrations to our Application
  • makemigrations - to identify differences in the model and create equivalent migration file for the changes
  • collectstatic - to collect static to base directory of the application

Django commands can have arguments to run, and we can call commands insider other modules as well. we can create our own commands for our applications.

lets create custom admin command where we want to just print some string.

from django.core.management.base import BaseCommand
import getpass

class Command(BaseCommand):
help="Says hello to users"

def handle(self, *args, **kwargs):
print(f"hello {getpass.getuser()}!")
  • The custom command is created under the management/commands folder of your app, the file name is considered a command name here, so ensure you give the proper name.
  • BaseCommand is the base call for creating all the commands. The commands class should be named "Command," as Django looks for this class to run the command.
  • We should also define the handle function; this is the function called when the command called from the CLI.
  • When we run the above command to list python manage commands, we should able see our command is picked up Django automatically.
(.env) ubuntu@DESKTOP-D3UU0QK:/mnt/d/codes/django-demo-admin-commands/command_demo$ python manage.py

Type 'manage.py help <subcommand>' for help on a specific subcommand.

Available subcommands:

[auth]
changepassword
createsuperuser

[contenttypes]
remove_stale_contenttypes

[django]
check
compilemessages
createcachetable
dbshell
diffsettings
dumpdata
flush
inspectdb
loaddata
makemessages
makemigrations
migrate
sendtestemail
shell
showmigrations
sqlflush
sqlmigrate
sqlsequencereset
squashmigrations
startapp
startproject
test
testserver

[helloworld]
say_hello

[sessions]
clearsessions

[staticfiles]
collectstatic
findstatic
runserver
  • and when we run our command it should print the "Hello ubuntu!" or with your system username.
(.env) ubuntu@DESKTOP-D3UU0QK:/mnt/d/codes/django-demo-admin-commands/command_demo$ python manage.py say_hello
hello ubuntu!

Lets enhance our command adding positional argument to command

from django.core.management.base import BaseCommand
import getpass

class Command(BaseCommand):
help="Says hello to users"

def add_arguments(self, parser):
parser.add_argument('name',type=str)

def handle(self, *args, **options):
print(f"hello {options['name']}!")
  • We have introduced a new function called add_arguments; this adds all the arguments which want to add to our command.
  • We have added one positional argument called 'name,' without this, our command will throw an error, we can also n number of parameters to our command, and they can be optional.
  • The commands parsed using argparse module, please follow the link for more information https://docs.python.org/3/library/argparse.html
(.env) ubuntu@DESKTOP-D3UU0QK:/mnt/d/codes/django-demo-admin-commands/command_demo$ python manage.py say_hello kamal
hello kamal!

We can also access the models and other Django apps inside your commands, this makes Django admin commands more effective to create any background jobs.

further readings

github link for working code: https://github.com/srkama/django-admin-commands