Django management command as a package?

390 Views Asked by At

I'm trying to have a directory structure for my custom django-admin commands.

According to the Django tutorial, commands are created as modules under the management/commands directory. e.g. management/commands/closepoll.py

I have many commands so I'm trying to split them into packages. I want to have a package structure, like:
management/commands/closepoll/closepoll.py <-- contains the Command class.
management/commands/closepoll/closepoll_utils.py
management/commands/closepoll/__init__.py

Tried that, but Django does not recognize the command.

1

There are 1 best solutions below

0
Abdul Aziz Barkat On

It is not possible since Django only searches the commands directory as we can see from the source code [GitHub]:

return [
    name
    for _, name, is_pkg in pkgutil.iter_modules([command_dir])
    if not is_pkg and not name.startswith("_")
]

What you can do is that you can have the Command class in the "commands" directory and the the other parts of the same can be in a package:

managment/
├─ __init__.py
├─ commands/
│  ├─ __init__.py
│  ├─ closepoll.py
│  ├─ closepoll_utils/
│  │  ├─ __init__.py

In case of the above example closepoll.py will have the Command class and what you had in closepoll_utils.py will be in closepoll_utils/__init__.py. In fact you can even have the Command class in your package and simply import it in closepoll.py.