Merge branch 'develop' into gilbert-ext4
[philo.git] / philo / models / fields / __init__.py
1 from django import forms
2 from django.core.exceptions import ValidationError
3 from django.core.validators import validate_slug
4 from django.db import models
5 from django.utils import simplejson as json
6 from django.utils.text import capfirst
7 from django.utils.translation import ugettext_lazy as _
8
9 from philo.forms.fields import JSONFormField
10 from philo.utils.registry import RegistryIterator
11 from philo.validators import TemplateValidator, json_validator
12 #from philo.models.fields.entities import *
13
14
15 class TemplateField(models.TextField):
16         """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction."""
17         def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs):
18                 super(TemplateField, self).__init__(*args, **kwargs)
19                 self.validators.append(TemplateValidator(allow, disallow, secure))
20
21
22 class JSONDescriptor(object):
23         def __init__(self, field):
24                 self.field = field
25         
26         def __get__(self, instance, owner):
27                 if instance is None:
28                         raise AttributeError # ?
29                 
30                 if self.field.name not in instance.__dict__:
31                         json_string = getattr(instance, self.field.attname)
32                         instance.__dict__[self.field.name] = json.loads(json_string)
33                 
34                 return instance.__dict__[self.field.name]
35         
36         def __set__(self, instance, value):
37                 instance.__dict__[self.field.name] = value
38                 setattr(instance, self.field.attname, json.dumps(value))
39         
40         def __delete__(self, instance):
41                 del(instance.__dict__[self.field.name])
42                 setattr(instance, self.field.attname, json.dumps(None))
43
44
45 class JSONField(models.TextField):
46         """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`."""
47         default_validators = [json_validator]
48         
49         def get_attname(self):
50                 return "%s_json" % self.name
51         
52         def contribute_to_class(self, cls, name):
53                 super(JSONField, self).contribute_to_class(cls, name)
54                 setattr(cls, name, JSONDescriptor(self))
55                 models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls)
56         
57         def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs):
58                 # Anything passed in as self.name is assumed to come from a serializer and
59                 # will be treated as a json string.
60                 if self.name in kwargs:
61                         value = kwargs.pop(self.name)
62                         
63                         # Hack to handle the xml serializer's handling of "null"
64                         if value is None:
65                                 value = 'null'
66                         
67                         kwargs[self.attname] = value
68         
69         def formfield(self, *args, **kwargs):
70                 kwargs["form_class"] = JSONFormField
71                 return super(JSONField, self).formfield(*args, **kwargs)
72
73
74 class SlugMultipleChoiceField(models.Field):
75         """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices."""
76         __metaclass__ = models.SubfieldBase
77         description = _("Comma-separated slug field")
78         
79         def get_internal_type(self):
80                 return "TextField"
81         
82         def to_python(self, value):
83                 if not value:
84                         return []
85                 
86                 if isinstance(value, list):
87                         return value
88                 
89                 return value.split(',')
90         
91         def get_prep_value(self, value):
92                 return ','.join(value)
93         
94         def formfield(self, **kwargs):
95                 # This is necessary because django hard-codes TypedChoiceField for things with choices.
96                 defaults = {
97                         'widget': forms.CheckboxSelectMultiple,
98                         'choices': self.get_choices(include_blank=False),
99                         'label': capfirst(self.verbose_name),
100                         'required': not self.blank,
101                         'help_text': self.help_text
102                 }
103                 if self.has_default():
104                         if callable(self.default):
105                                 defaults['initial'] = self.default
106                                 defaults['show_hidden_initial'] = True
107                         else:
108                                 defaults['initial'] = self.get_default()
109                 
110                 for k in kwargs.keys():
111                         if k not in ('coerce', 'empty_value', 'choices', 'required',
112                                                  'widget', 'label', 'initial', 'help_text',
113                                                  'error_messages', 'show_hidden_initial'):
114                                 del kwargs[k]
115                 
116                 defaults.update(kwargs)
117                 form_class = forms.TypedMultipleChoiceField
118                 return form_class(**defaults)
119         
120         def validate(self, value, model_instance):
121                 invalid_values = []
122                 for val in value:
123                         try:
124                                 validate_slug(val)
125                         except ValidationError:
126                                 invalid_values.append(val)
127                 
128                 if invalid_values:
129                         # should really make a custom message.
130                         raise ValidationError(self.error_messages['invalid_choice'] % invalid_values)
131         
132         def _get_choices(self):
133                 if isinstance(self._choices, RegistryIterator):
134                         return self._choices.copy()
135                 elif hasattr(self._choices, 'next'):
136                         choices, self._choices = itertools.tee(self._choices)
137                         return choices
138                 else:
139                         return self._choices
140         choices = property(_get_choices)
141
142
143 try:
144         from south.modelsinspector import add_introspection_rules
145 except ImportError:
146         pass
147 else:
148         add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"])
149         add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"])
150         add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])