[Django]-Django custom management commands: AttributeError: 'module' object has no attribute 'Command'

5👍

What is your file structure like? It should be like so:

app/
    __init__.py
    management/
        __init__.py
        commands/
            __init__.py
            event_expiration.py

If the structure is as above, try the following:

python manage.py shell
>>> from app.management.commands import event_expiration
>>> dir(event_expiration)
['Account', 'BaseCommand', 'Callback', 'Command', 'CommandError', 'Comment', 'Status', 'User', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'clean_phone_number', 'csv', 'models', 'os', 're']

I’ve listed the pure output of running dir on a management command of my own. Give that a try, and report back what is available to the module. You might find yourself getting an error at this point, which may help diagnose. I’m suspecting a problem with importing django itself. I’m guessing the python manage.py shell will fail, which will mean it’s not a problem with your command, but a problem with the project.

Edit 2:

The fact that check_expiration was visible in your dir output supports my theory that the folder structure is amiss in someway. Unless there’s specifically a function named that within your module.

Please do the following and show the output:

cd /path/to/app/
find .

Also, show the entire contents of your event_expiration.py file, and the contents of your management/commands/__init__.py file. Be wary of spaces mixed with tabs as whitespace also.

35👍

I ran into the same issue and the problem was that my command class wasn’t called exactly Command, as the docs says. Example:

class Command(NoArgsCommand):
    # Do something here

0👍

Printing a queryset directly will also cause this error. For instance, I was trying to do something like this (just testing, not a real use case):

    def handle(self, *args, **options):
       ppl = People.objects.all()
       print(ppl)

Resolution:

    def handle(self, *args, **options):
       ppl = People.objects.all()
       print(str(ppl)) # Convert queryset to string

Conclusion: What works in shell doesn’t necessarily work in a management command. Would be nice if someone can point out why.

-1👍

I got this error by importing the regular click module instead of djclick

my_module/management/commands/run_thing.py

# import click  # causes the error because not setup like djclick is
import djclick as click

@click.command()
@click.option("--thing", required=True, prompt=True)
def command(thing):
    print(f"hi: {thing}"

Example run:

./manage.py run_thing --thing 123
...
hi: 123

Leave a comment