2 from django.utils.encoding import force_unicode
4 class SettingSet(list):
5 def __init__(self, name, title, description, weight=1000, markdown=False):
8 self.description = description
10 self.markdown = markdown
13 class BaseSetting(object):
15 def add_to_class(cls, name):
16 def wrapper(self, *args, **kwargs):
17 return self.value.__getattribute__(name)(*args, **kwargs)
19 setattr(cls, name, wrapper)
21 def __init__(self, name, default, set=None, field_context=None):
23 self.default = default
24 self.field_context = field_context or {}
27 if not set.name in Setting.sets:
28 Setting.sets[set.name] = set
30 Setting.sets[set.name].append(self)
33 return str(self.value)
35 def __unicode__(self):
36 return unicode(self.value)
40 from forum.models import KeyValue
43 kv = KeyValue.objects.get(key=self.name)
45 kv = KeyValue(key=self.name, value=self._parse(self.default))
50 def set_value(self, new_value):
51 new_value = self._parse(new_value)
54 def save(self, value):
55 from forum.models import KeyValue
58 kv = KeyValue.objects.get(key=self.name)
60 kv = KeyValue(key=self.name)
66 self.set_value(self.default)
68 def _parse(self, value):
69 if not isinstance(value, self.base_type):
71 return self.base_type(value)
76 class AnyTypeSetting(BaseSetting):
77 def _parse(self, value):
81 class Setting(object):
85 def __new__(cls, name, default, set=None, field_context=None):
87 return AnyTypeSetting(name, default, set, field_context)
89 deftype = type(default)
91 if deftype in Setting.emulators:
92 emul = Setting.emulators[deftype]
94 emul = type(deftype.__name__ + cls.__name__, (BaseSetting,), {'base_type': deftype})
96 fns = [n for n, f in [(p, getattr(deftype, p)) for p in dir(deftype) if not p in dir(cls)] if callable(f)]
101 Setting.emulators[deftype] = emul
103 return emul(name, default, set, field_context)