Made a slight change to window position randomization; now only non-modal windows...
[philo.git] / models / fields / __init__.py
1 from django import forms
2 from django.db import models
3 from django.utils import simplejson as json
4 from philo.forms.fields import JSONFormField
5 from philo.validators import TemplateValidator, json_validator
6 #from philo.models.fields.entities import *
7
8
9 class TemplateField(models.TextField):
10         def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs):
11                 super(TemplateField, self).__init__(*args, **kwargs)
12                 self.validators.append(TemplateValidator(allow, disallow, secure))
13
14
15 class JSONDescriptor(object):
16         def __init__(self, field):
17                 self.field = field
18         
19         def __get__(self, instance, owner):
20                 if instance is None:
21                         raise AttributeError # ?
22                 
23                 if self.field.name not in instance.__dict__:
24                         json_string = getattr(instance, self.field.attname)
25                         instance.__dict__[self.field.name] = json.loads(json_string)
26                 
27                 return instance.__dict__[self.field.name]
28         
29         def __set__(self, instance, value):
30                 instance.__dict__[self.field.name] = value
31                 setattr(instance, self.field.attname, json.dumps(value))
32         
33         def __delete__(self, instance):
34                 del(instance.__dict__[self.field.name])
35                 setattr(instance, self.field.attname, json.dumps(None))
36
37
38 class JSONField(models.TextField):
39         default_validators = [json_validator]
40         
41         def get_attname(self):
42                 return "%s_json" % self.name
43         
44         def contribute_to_class(self, cls, name):
45                 super(JSONField, self).contribute_to_class(cls, name)
46                 setattr(cls, name, JSONDescriptor(self))
47                 models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls)
48         
49         def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs):
50                 if self.name in kwargs:
51                         kwargs[self.attname] = json.dumps(kwargs.pop(self.name))
52         
53         def formfield(self, *args, **kwargs):
54                 kwargs["form_class"] = JSONFormField
55                 return super(JSONField, self).formfield(*args, **kwargs)
56
57
58 try:
59         from south.modelsinspector import add_introspection_rules
60 except ImportError:
61         pass
62 else:
63         add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"])
64         add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])