django custom command not found

Viewed 27508

Having issues getting django custom commands to work.

From django documetation, have placed

application/
    manage.py
    blog/
        __init__.py
        models.py
        management/
            __init__.py
            commands/
                __init__.py
                myapp_task.py
        views.py

myapp_task.py content is

from django.core.management.base import NoArgsCommand

class Command(NoArgsCommand):
    def handle_noargs(self, **options):
        print 'Doing task...'
        # invoke the functions you need to run on your project here
        print 'Done'

when ran

python manage.py myapp_task

getting error

Unknown command: 'myapp_task'
8 Answers

The directory structure in your answer is a little ambiguous; when placing the files as follows django should be able to find your command:

project/ # in your question this would be 'application'
    manage.py
    blog/
        __init__.py
        models.py
        management/
            __init__.py
            commands/
                __init__.py
                myapp_task.py
        views.py

Furthermore, you'll need to enable your app in your settings.py:

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.admin',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'blog', # <= your app here ...
)

My problem was I was adding the management directory in my main app besides my settings.py file once I have added it to another app it worked

I had this same problem. I had cut and paste the filename from an example and had paste a space at the start of the filename. Therefore Django could not find it.

I think commands/ needs to be inside the management/ directory.

Hi I also had this problem and found out I was mixing up the argument identifier with the file name

so the file is the name of the command you want i.e. updater I changed updatefiles.py to updater.py

class Command(BaseCommand):
    help = 'Update Files Since \'X\' Days Ago'   

    def add_arguments(self, parser):
        parser.add_argument('updatefiles', nargs='+', type=int)

    def handle(self, *args, **options):

        days_ago = int(options['updatefiles'][0])
        days_ago = (days_ago * -1) if days_ago < 0 else days_ago

        self.stdout.write('Adding files since %s days ago' % days_ago)
        add_files_function(days_ago)

then to run I would use

python manage.py updater
Related