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 _
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 *
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))
22 class JSONDescriptor(object):
23 def __init__(self, field):
26 def __get__(self, instance, owner):
28 raise AttributeError # ?
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)
34 return instance.__dict__[self.field.name]
36 def __set__(self, instance, value):
37 instance.__dict__[self.field.name] = value
38 setattr(instance, self.field.attname, json.dumps(value))
40 def __delete__(self, instance):
41 del(instance.__dict__[self.field.name])
42 setattr(instance, self.field.attname, json.dumps(None))
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]
49 def get_attname(self):
50 return "%s_json" % self.name
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)
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)
63 # Hack to handle the xml serializer's handling of "null"
67 kwargs[self.attname] = value
69 def formfield(self, *args, **kwargs):
70 kwargs["form_class"] = JSONFormField
71 return super(JSONField, self).formfield(*args, **kwargs)
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")
79 def get_internal_type(self):
82 def to_python(self, value):
86 if isinstance(value, list):
89 return value.split(',')
91 def get_prep_value(self, value):
92 return ','.join(value)
94 def formfield(self, **kwargs):
95 # This is necessary because django hard-codes TypedChoiceField for things with choices.
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
103 if self.has_default():
104 if callable(self.default):
105 defaults['initial'] = self.default
106 defaults['show_hidden_initial'] = True
108 defaults['initial'] = self.get_default()
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'):
116 defaults.update(kwargs)
117 form_class = forms.TypedMultipleChoiceField
118 return form_class(**defaults)
120 def validate(self, value, model_instance):
125 except ValidationError:
126 invalid_values.append(val)
129 # should really make a custom message.
130 raise ValidationError(self.error_messages['invalid_choice'] % invalid_values)
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)
140 choices = property(_get_choices)
144 from south.modelsinspector import add_introspection_rules
148 add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"])
149 add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"])
150 add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])