Django custom commands


What's inside this article ⌄
  • Django custom management commands
  • Django command line extension
  • Django management command example
  • Python manage.py custom commands

Creating custom commands in Django is a powerful way to extend the functionality of your project by defining your own management commands. These commands can be used to automate tasks, perform periodic maintenance, or execute any custom functionality you need.

Basically, they behave the same as your code in the Django shell. The difference here is that custom Django commands are already prepared and exist as scripts that are stored within your project in a designated place.

I encourage you to check out this article to get a sense of it.

Let’s look at the example of creating a custom command. Suppose you have the GreetService somewhere in your Django project:

class GreetService:
   def __init__(self, name):
      self.name = name

   def execute(self) -> str:
      return f"Hello, {self.name}!"

You can make a custom Django command, subsequently importing and making use of that service:

  1. Create nested packages (not a folders) management/commands under the root of your Django app (not the root of your Django project).

  2. Make sure your app is registered under INSTALLED_APPS.

  3. Create a file named greet_command.py under the commands package you created in the first step.

  4. The code for the greet_command will be as described below.

from django.contrib.auth.models import User
from django.core.management import BaseCommand
from testapp.services.greet_service import GreetService

class Command(BaseCommand):
   help = 'My custom command description'

   def handle(self, *args, **options):
      for user in User.objects.all():
         print(GreetService(user.username).execute())

It remains only to launch the command:

python manage.py greet_command

Here you go!