Skip to content

How to Create Django Custom Management Commands with Example

how to add custom commands in django

To add custom commands in Django, you can create a new file in your app’s directory called “management/commands” and then create a new Python file within that directory. The file should be named after the command you want to create, such as “mycommand.py”.

Django management commands example:

Here is an example of a custom command called “greet” that simply prints “Hello, world!” when run:

#your_app/management/commands/greet.py

from django.core.management.base import BaseCommand

class Command(BaseCommand):
   #help text
    help = 'Prints a greeting'

    def handle(self, *args, **options):
        print("Hello, world!")

To use this command, you would run it from the command line using the following command:

#django run custom command

python manage.py greet

Note: if you make any spelling mistake it will occur “django custom command not found

Django management command arguments example:

You can also pass arguments and options to your custom command. Here’s an example of a command that takes a single argument and an option:

#your_app/management/commands/greet.py

from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = 'Prints a greeting to the given name'

    #django custom command args
    def add_arguments(self, parser):
        parser.add_argument('name', type=str, help='The name to greet')
        parser.add_argument('--uppercase', action='store_true', help='Print the greeting in uppercase')

    #customize as you want
    def handle(self, *args, **options):
        name = options['name']
        greeting = f"Hello, {name}!"
        if options['uppercase']:
            greeting = greeting.upper()
        self.stdout.write(greeting)

You can use this command as follows:

#django management command required argument

python manage.py greet --name=Bidyut --uppercase

This command will greet Bidyut in uppercase.

Note that you should define your command class as Command as it is a subclass of BaseCommand and it is what Django uses to find and run your command.

Django add custom manage.py command dry_run:

how you could add a dry_run option to the django create custom command that creates a new user in the database:

#your_app/management/commands/createuser.py

from django.core.management.base import BaseCommand
from django.contrib.auth.models import User

class Command(BaseCommand):
    help = 'Create a new user with the given username and email'

    def add_arguments(self, parser):
        parser.add_argument('username', type=str, help='The username for the new user')
        parser.add_argument('email', type=str, help='The email for the new user')
        parser.add_argument('password', type=str, help='The password for the new user')
        parser.add_argument('--dry-run', action='store_true', help='Does not create the user, only shows what would be done')

    #django manage.py custom commands
    def handle(self, *args, **options):
        username = options['username']
        email = options['email']
        password = options['password']
        dry_run = options['dry_run']

        #django test custom command --only for testing things
        if dry_run:
            self.stdout.write(f'Dry run: Would create user {username} with email {email}')
        else:
            user = User.objects.create_user(username, email, password)
            self.stdout.write(self.style.SUCCESS(f'Successfully created user {username}'))

This command takes an additional option called dry-run which when set to true, it will show what would be done but not create the user. You can use this command as follows:

#django call custom command args

python manage.py createuser --username=bidyut_maji --email=bidyut@theubuntulinux.com --password=secretpassword --dry-run

This django execute custom command will show what would be done if you create a new user with the given username, email, and password, but do not create the user.

If you don’t include the –dry-run argument, the user will be created as usual.

The Short Note:

Custom commands in Django are a powerful tool for streamlining app management and automating repetitive tasks. This tutorial has provided a comprehensive guide to creating custom commands, complete with real-world examples and tips for best practices. Like custom commands, learn how to customize user model.

Related tutorial: How to create custom model fields in Django

Leave a Reply

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