From 22bfb93504ea1d496e734ccbefd529f9d79ab5c3 Mon Sep 17 00:00:00 2001 From: Roberto Rosario Date: Sat, 18 Aug 2012 10:25:34 -0400 Subject: [PATCH] Add Choice class --- apps/common/utils.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/apps/common/utils.py b/apps/common/utils.py index 0ed05807d0..a60d0c9510 100644 --- a/apps/common/utils.py +++ b/apps/common/utils.py @@ -433,3 +433,25 @@ def copyfile(source, destination, buffer_size=1024 * 1024): source_descriptor.close() destination_descriptor.close() + + + +#From: http://tomforb.es/using-python-metaclasses-to-make-awesome-django-model-field-choices?pid=0&utm_source=agiliq&utm_medium=agiliq +import inspect + +class Choice(object): + class __metaclass__(type): + def __init__(self, name, type, other): + self._data = [] + for name, value in inspect.getmembers(self): + if not name.startswith('_') and not inspect.isfunction(value): + if isinstance(value,tuple) and len(value) > 1: + data = value + else: + data = (value, ' '.join([x.capitalize() for x in name.split('_')]),) + self._data.append(data) + setattr(self, name, data[0]) + + def __iter__(self): + for value, data in self._data: + yield value, data