Search code examples
pythondjangocommandstructurecustomization

Can I have a folder instead file for a Django custom command?


The only way I know to create a custom Django command is by putting the file in the project/app/management/commands folder like this project/app/management/commands/my_custom_command.py

But I would like to know if there is a way to make a directory (like a python package) instead of a single file. It should be something like this:

project
├── app
|   ├── management
|   |   └── commands
|   |       ├── my_custom_command
|   |       |   ├── __init__.py
|   |       |   └── ... (other stuff like settings and output files)
|   |       └── ...
|   └── ...
├── manage.py
└── ...

There is a way to do something like that? I think it is possible to use a whole app folder to do something similar by saving the command stuff in the app folder, but I don't like that solution.

Clarification: I already tried using a folder with the __init__.py file but it didn't work.


Solution

  • It is not possible, packages are excluded, see django.core.management.find_commands

    In Django 3.1.5 it is:

    def find_commands(management_dir):
        """
        Given a path to a management directory, return a list of all the command
        names that are available.
        """
        command_dir = os.path.join(management_dir, 'commands')
        return [name for _, name, is_pkg in pkgutil.iter_modules([command_dir])
                if not is_pkg and not name.startswith('_')]