Writing a custom management command with args and options – explanation of fields needed

Explanation of make_option from the docs http://docs.python.org/2/library/optparse.html#populating-the-parser

make_option() is a factory function for creating Option instances;
currently it is an alias for the Option constructor. A future version
of optparse may split Option into several classes, and make_option()
will pick the right class to instantiate. Do not instantiate Option
directly.

These are all of the possible option attributes:

http://docs.python.org/2/library/optparse.html#option-attributes

Common Use in a django management command:

class Command(BaseCommand):
    help = "Command to import a list of X"
    option_list = BaseCommand.option_list + (
        make_option(
            "-f", 
            "--file", 
            dest = "filename",
            help = "specify import file", 
            metavar = "FILE"
        ),
    )

    option_list = option_list + (
        make_option(
            "-s", 
            "--slug", 
            dest = "category",
            help = "category slug", 
            metavar = "SLUG"
        ),
    )

    def handle(self, *args, **options):
            # make sure file option is present
            if options['filename'] == None :
                raise CommandError("Option `--file=...` must be specified.")
        
            # make sure file path resolves
            if not os.path.isfile(options['filename']) :
                raise CommandError("File does not exist at the specified path.")
    
            # make sure form option is present
            if options['category'] == None :
                raise CommandError("Option `--slug=...` must be specified.")

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)