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.validators import TemplateValidator, json_validator
11 from philo.forms.widgets import EmbedWidget
12 #from philo.models.fields.entities import *
15 class TemplateField(models.Field):
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))
21 def formfield(self, **kwargs):
22 defaults = {'widget': EmbedWidget}
23 defaults.update(kwargs)
24 return super(TemplateField, self).formfield(**defaults)
27 class JSONDescriptor(object):
28 def __init__(self, field):
31 def __get__(self, instance, owner):
33 raise AttributeError # ?
35 if self.field.name not in instance.__dict__:
36 json_string = getattr(instance, self.field.attname)
37 instance.__dict__[self.field.name] = json.loads(json_string)
39 return instance.__dict__[self.field.name]
41 def __set__(self, instance, value):
42 instance.__dict__[self.field.name] = value
43 setattr(instance, self.field.attname, json.dumps(value))
45 def __delete__(self, instance):
46 del(instance.__dict__[self.field.name])
47 setattr(instance, self.field.attname, json.dumps(None))
50 class JSONField(models.TextField):
51 """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`."""
52 default_validators = [json_validator]
54 def get_attname(self):
55 return "%s_json" % self.name
57 def contribute_to_class(self, cls, name):
58 super(JSONField, self).contribute_to_class(cls, name)
59 setattr(cls, name, JSONDescriptor(self))
60 models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls)
62 def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs):
63 # Anything passed in as self.name is assumed to come from a serializer and
64 # will be treated as a json string.
65 if self.name in kwargs:
66 value = kwargs.pop(self.name)
68 # Hack to handle the xml serializer's handling of "null"
72 kwargs[self.attname] = value
74 def formfield(self, *args, **kwargs):
75 kwargs["form_class"] = JSONFormField
76 return super(JSONField, self).formfield(*args, **kwargs)
79 class SlugMultipleChoiceField(models.Field):
80 """Stores a selection of multiple items with unique slugs in the form of a comma-separated list."""
81 __metaclass__ = models.SubfieldBase
82 description = _("Comma-separated slug field")
84 def get_internal_type(self):
87 def to_python(self, value):
91 if isinstance(value, list):
94 return value.split(',')
96 def get_prep_value(self, value):
97 return ','.join(value)
99 def formfield(self, **kwargs):
100 # This is necessary because django hard-codes TypedChoiceField for things with choices.
102 'widget': forms.CheckboxSelectMultiple,
103 'choices': self.get_choices(include_blank=False),
104 'label': capfirst(self.verbose_name),
105 'required': not self.blank,
106 'help_text': self.help_text
108 if self.has_default():
109 if callable(self.default):
110 defaults['initial'] = self.default
111 defaults['show_hidden_initial'] = True
113 defaults['initial'] = self.get_default()
115 for k in kwargs.keys():
116 if k not in ('coerce', 'empty_value', 'choices', 'required',
117 'widget', 'label', 'initial', 'help_text',
118 'error_messages', 'show_hidden_initial'):
121 defaults.update(kwargs)
122 form_class = forms.TypedMultipleChoiceField
123 return form_class(**defaults)
125 def validate(self, value, model_instance):
130 except ValidationError:
131 invalid_values.append(val)
134 # should really make a custom message.
135 raise ValidationError(self.error_messages['invalid_choice'] % invalid_values)
139 from south.modelsinspector import add_introspection_rules
143 add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"])
144 add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"])
145 add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])