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 *
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))
15 class JSONDescriptor(object):
16 def __init__(self, field):
19 def __get__(self, instance, owner):
21 raise AttributeError # ?
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)
27 return instance.__dict__[self.field.name]
29 def __set__(self, instance, value):
30 instance.__dict__[self.field.name] = value
31 setattr(instance, self.field.attname, json.dumps(value))
33 def __delete__(self, instance):
34 del(instance.__dict__[self.field.name])
35 setattr(instance, self.field.attname, json.dumps(None))
38 class JSONField(models.TextField):
39 default_validators = [json_validator]
41 def get_attname(self):
42 return "%s_json" % self.name
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)
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))
53 def formfield(self, *args, **kwargs):
54 kwargs["form_class"] = JSONFormField
55 return super(JSONField, self).formfield(*args, **kwargs)
59 from south.modelsinspector import add_introspection_rules
63 add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"])
64 add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])