Only allow users to add NPC or Player characters.
[matthijs/projects/xerxes.git] / tools / misc.py
index 110c370a74500672c1749dbaf4bb4b9f7c115ae8..ddc6cee7490dc6fc3492376f5e004821827b2952 100644 (file)
@@ -13,3 +13,47 @@ def make_iter(value):
         except TypeError:
             pass
     return [value]
+# vim: set sts=4 sw=4 expandtab:
+
+"""
+Decarator that catches any exception raised by the decorated function,
+prints it to stdout and raises it again.
+"""
+def log_error(func):
+    def show(*args, **kwargs):
+        try:
+            return func(*args, **kwargs)
+        except Exception, e:
+            import traceback
+            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]