How to get a list of all custom Django commands in a project?

Question:

I want to find a custom command in a project with many apps, how to get a list of all commands from all apps?

Asked By: Sashko Lykhenko

||

Answers:

This command will list all the custom or existing command of all installed apps:

python manage.py help
Answered By: sankalp

You can also load django commands using a django module.

To get a list of all custom Django commands in a project, you can use the from django.core.management import get_commands. This get_commands function returns a dictionary of all available commands and their associated applications from the running application.

Here is an example of how you can use this function to display all commands and their associated applications:

from django.core.management import get_commands

commands = get_commands()
print([command for command in commands.items()])
#sample output 

$ [('check', 'django.core'),
 ('compilemessages', 'django.core'),
 ('createcachetable', 'django.core'),
 ('dbshell', 'django.core'),
 ('diffsettings', 'django.core'),
 ('dumpdata', 'django.core'),
 ('flush', 'django.core'),
 ('inspectdb', 'django.core'),
 ('loaddata', 'django.core'),
 ('makemessages', 'commands'),
 ('makemigrations', 'django_migration_linter'),
 ('migrate', 'django.core'),
 ('runserver', 'django.contrib.staticfiles'),
 ('sendtestemail', 'django.core'),
 ('shell', 'django.core'),
]

If you want to display only the commands for a specific application, you can filter the results of get_commands() using the following code:

[command for command in commands.items() if command[1] == 'app_name']

Replace ‘app_name’ with the name of the application you want to display the commands for.

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.