Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one use Django custom management command option?

The Django doc tell me how to add an option to my django custom management command, via an example:

from optparse import make_option

class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('--delete',
            action='store_true',
            dest='delete',
            default=False,
            help='Delete poll instead of closing it'),
    )

Then the docs just stop. How would one write the handle method for this class to check whether the user has supplied a --delete option? At times Django makes the easy things difficult :-(

like image 893
peter2108 Avatar asked Nov 17 '10 18:11

peter2108


People also ask

What is custom management command Django?

Manage.py in Django is a command-line utility that works similar to the django-admin command. The difference is that it points towards the project's settings.py file. This manage.py utility provides various commands that you must have while working with Django.

How do you pass arguments in Django management command?

The parameter parser is an instance of argparse. ArgumentParser (see the docs). Now you can add as many arguments as you want by calling parser 's add_argument method. In the code above, you are expecting a parameter n of type int which is gotten in the handle method from options .

What does the Django management command Inspectdb do?

inspectdb. Introspects the database tables in the database pointed-to by the NAME setting and outputs a Django model module (a models.py file) to standard output.


1 Answers

You can do it like this:

from optparse import make_option

class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('--del',
            action='store_true',
            help='Delete poll'),
        make_option('--close',
            action='store_true',
            help='Close poll'),
    )

    def handle(self, close, *args, **kwargs):
        del_ = kwargs.get('del')

Do note that some keywords in Python are reserved so you can handle those using **kwargs. Otherwise you can use normal arguments (like I did with close)

like image 79
Wolph Avatar answered Oct 18 '22 16:10

Wolph