pythondjangopython-2.7django-commands

Calling a Django command in a unittest code


I am trying to use call_command to download data from a URL and was wondering on how to call it from the code.

I have declared the option lists as follows in my code:

option_list = BaseCommand.option_list + (
        make_option('--url', default=None, dest='url', help=_(u'Specifies the full url of the json data to download.')),
        make_option('--username', default=None, dest='username', help=_(u'Login of the person doing the download.')),
        make_option('--password', default=None, dest='password', help=_(u'Password of the person doing the download.')),
        make_option('--file', default=None, dest='file', help=_(u'File name of the json data to download in gzip-compressed-data format')),
    )

I use it as follows from the command line:

./manage.py download --url=http://some-link.com/download/ --username=admin --password=admin

So far I have the following:

call_command('download')

How do I pass in the rest of the parameters/args?


Solution

  • Just pass them as keyword arguments:

    call_command('download', 
                 url="http://some-link.com/download/", 
                 username="admin",
                 password="admin")
    

    The keyword arguments should reflect the dest values of your custom management command arguments.


    Example for flush command:

    --initial-data command-line argument in call_command() can be set by passing load_initial_data keyword argument:

    call_command('flush', load_initial_data=False)
    

    This is because it is --initial-data's argument destination:

    parser.add_argument('--no-initial-data', action='store_false',
        dest='load_initial_data', default=True,
        help='Tells Django not to load any initial data after database synchronization.')