Initial work on a widget for TemplateFields that allows javascript selection of an...
[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.validators import TemplateValidator, json_validator
11 from philo.forms.widgets import EmbedWidget
12 #from philo.models.fields.entities import *
13
14
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))
20         
21         def formfield(self, **kwargs):
22                 defaults = {'widget': EmbedWidget}
23                 defaults.update(kwargs)
24                 return super(TemplateField, self).formfield(**defaults)
25
26
27 class JSONDescriptor(object):
28         def __init__(self, field):
29                 self.field = field
30         
31         def __get__(self, instance, owner):
32                 if instance is None:
33                         raise AttributeError # ?
34                 
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)
38                 
39                 return instance.__dict__[self.field.name]
40         
41         def __set__(self, instance, value):
42                 instance.__dict__[self.field.name] = value
43                 setattr(instance, self.field.attname, json.dumps(value))
44         
45         def __delete__(self, instance):
46                 del(instance.__dict__[self.field.name])
47                 setattr(instance, self.field.attname, json.dumps(None))
48
49
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]
53         
54         def get_attname(self):
55                 return "%s_json" % self.name
56         
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)
61         
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)
67                         
68                         # Hack to handle the xml serializer's handling of "null"
69                         if value is None:
70                                 value = 'null'
71                         
72                         kwargs[self.attname] = value
73         
74         def formfield(self, *args, **kwargs):
75                 kwargs["form_class"] = JSONFormField
76                 return super(JSONField, self).formfield(*args, **kwargs)
77
78
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")
83         
84         def get_internal_type(self):
85                 return "TextField"
86         
87         def to_python(self, value):
88                 if not value:
89                         return []
90                 
91                 if isinstance(value, list):
92                         return value
93                 
94                 return value.split(',')
95         
96         def get_prep_value(self, value):
97                 return ','.join(value)
98         
99         def formfield(self, **kwargs):
100                 # This is necessary because django hard-codes TypedChoiceField for things with choices.
101                 defaults = {
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
107                 }
108                 if self.has_default():
109                         if callable(self.default):
110                                 defaults['initial'] = self.default
111                                 defaults['show_hidden_initial'] = True
112                         else:
113                                 defaults['initial'] = self.get_default()
114                 
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'):
119                                 del kwargs[k]
120                 
121                 defaults.update(kwargs)
122                 form_class = forms.TypedMultipleChoiceField
123                 return form_class(**defaults)
124         
125         def validate(self, value, model_instance):
126                 invalid_values = []
127                 for val in value:
128                         try:
129                                 validate_slug(val)
130                         except ValidationError:
131                                 invalid_values.append(val)
132                 
133                 if invalid_values:
134                         # should really make a custom message.
135                         raise ValidationError(self.error_messages['invalid_choice'] % invalid_values)
136
137
138 try:
139         from south.modelsinspector import add_introspection_rules
140 except ImportError:
141         pass
142 else:
143         add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"])
144         add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"])
145         add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])