X-Git-Url: https://git.stderr.nl/gitweb?a=blobdiff_plain;f=tools%2Fmisc.py;h=ddc6cee7490dc6fc3492376f5e004821827b2952;hb=HEAD;hp=ba84f05e87141c0be4a9e2efd14bdf1d906dbc1d;hpb=4bd2ee34c818b499888d3f0bb52ffbf1eb58580b;p=matthijs%2Fprojects%2Fxerxes.git diff --git a/tools/misc.py b/tools/misc.py index ba84f05..ddc6cee 100644 --- a/tools/misc.py +++ b/tools/misc.py @@ -28,3 +28,32 @@ def log_error(func): traceback.print_exc() raise e return show + +def make_choices(objects): + """ + Transforms a list (or iteratable) of model objects to a list + suitable to be used as a list of choices in form widgets like + Select. + + This fullfills a similar (but simpler) function as + django.forms.models.ModelChoiceIterator, but that one requires a + FormField and is not public. + """ + return [(o.pk, o) for o in objects] + +def filter_choices(choices, filter): + """ + Returns the given choices list with only the choices with the names + in filter left. For example, when a model defines + A = 'A' + B = 'B' + FOO_CHOICES = ( + (A, "Foo A"), + (B, "Foo B") + ) + + you can later define a modelfield using + + foo = ChoiceField(choices=filter_choices(Foo.FOO_CHOICES, [Foo.A])) + """ + return [(name, value) for (name, value) in choices if name in filter]