Générateur d'options pour ChoiceField
Ce script construit une liste de choix, en respectant la syntaxe
attendue par Django pour ses ChoiceField. Il ne reste plus qu'à
#! env python
# -*- coding: utf-8 -*-
""" cfcg: Choice Field Choices Generator.
Generate tuple style choices list like django required
The key is the index of the value in the list
"""
import sys
def print_usage(*args, **kwargs):
""" Print usages of the cfcg command """
if not kwargs.get('ask_keys', False):
print """usage: cfcg [-q] choice [choice choice ...]
-q/--ask: Ask the key for each choices
-h/--help: Print this usage
"""
else:
print """usage: gen_choices_list -q choice [choice choice ...]
-q/--ask: Ask the key for each choices
-h/--help: Print this usage
"""
print "cfcg: Choice Field Choices Generator\n"
def parse_args(args, **kwargs):
""" Parse arguments and return options and args """
opts = {
'help': False,
'ask_keys': False
}
if "-h" in args:
args.pop(args.index('-h'))
opts['help'] = True
if "--help" in args:
args.pop(args.index('--help'))
opts['help'] = True
if '-q' in args:
opts['ask_keys'] = True
args.pop(args.index('-q'))
if '--ask' in args:
args.pop(args.index('--ask'))
opts['ask_keys'] = True
return args, opts
class TooFewArgumentException(Exception):
""" Particular Exception for the script """
def __init__(self, *args, **kwargs):
super(TooFewArgumentException, self).__init__('Error: Too few arguments')
def get_tuple(args, **kwargs):
""" Construct the tuple from the args.
Ask for key if needed
"""
if not args:
raise TooFewArgumentException()
if kwargs.get('ask_keys', False):
print 'Give the key for each options'
return tuple((raw_input('%s: ' % w), w) for w in args)
return tuple((i, w) for i,w in enumerate(args))
if __name__ == "__main__":
args, opts = parse_args(sys.argv[1:])
try:
if opts['help']:
print_usage(**opts)
else:
print get_tuple(args, **opts)
except TooFewArgumentException as e:
print_usage(**opts)
print(e)
exit(1)
exit(0)
L'utilisation est on ne peut plus simple :
$ cfcg Online Offline Invisible
((0, 'Online'), (1, 'Offline'), (2, 'Away'), (3, 'Busy'), (4, 'Invisble'))
Vous copier ça en tant qu'options de votre ChoiceField (à supposer qu'il
prenne bien un int en valeur) et ça roule !