Last active
August 29, 2015 13:55
-
-
Save renskiy/8781552 to your computer and use it in GitHub Desktop.
Add support of `optparse.OptionGroup` for Django commands
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Add support of `optparse.OptionGroup` for Django commands. | |
| Example: | |
| class MyCommand(AdvancedCommand): | |
| option_groups = AdvancedCommand.option_groups + ( | |
| make_option_group( | |
| 'Option group title', | |
| description='Option group description', | |
| option_list=( | |
| make_option('-option', help='Some option',), | |
| # additional group options... | |
| ), | |
| ), | |
| # additional option groups... | |
| ) | |
| """ | |
| from django.core.management import BaseCommand | |
| from optparse import OptionGroup | |
| def make_option_group(title, description=None, option_list=None): | |
| option_list = option_list or [] | |
| return (title, description), option_list | |
| class AdvancedCommand(BaseCommand): | |
| """ | |
| Class: AdvancedCommand | |
| Extended Django's BaseCommand with option groups | |
| """ | |
| option_groups = () | |
| def create_parser(self, *args, **kwargs): | |
| parser = super(AdvancedCommand, self).create_parser(*args, **kwargs) | |
| for option_group_args, option_list in self.option_groups: | |
| option_group = OptionGroup(parser, *option_group_args) | |
| option_group.add_options(option_list) | |
| parser.add_option_group(option_group) | |
| return parser |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
note that the
call_commandfunction (up to v1.7 ...1.8 uses argparse instead now) looks directly atklass.option_listattribute so it won't work with commands defined as above