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)
77 class Setting(object):
81 def __new__(cls, name, default, set=None, field_context=None):
82 deftype = type(default)
84 if deftype in Setting.emulators:
85 emul = Setting.emulators[deftype]
87 emul = type(deftype.__name__ + cls.__name__, (BaseSetting,), {'base_type': deftype})
89 fns = [n for n, f in [(p, getattr(deftype, p)) for p in dir(deftype) if not p in dir(cls)] if callable(f)]
94 Setting.emulators[deftype] = emul
96 return emul(name, default, set, field_context)