Merge branch 'master' into flexible_attributes
[philo.git] / forms.py
1 from django import forms
2 from django.contrib.admin.widgets import AdminTextareaWidget
3 from django.core.exceptions import ValidationError, ObjectDoesNotExist
4 from django.db.models import Q
5 from django.forms.models import model_to_dict, fields_for_model, ModelFormMetaclass, ModelForm, BaseInlineFormSet
6 from django.forms.formsets import TOTAL_FORM_COUNT
7 from django.template import loader, loader_tags, TemplateDoesNotExist, Context, Template as DjangoTemplate
8 from django.utils.datastructures import SortedDict
9 from philo.admin.widgets import ModelLookupWidget
10 from philo.models import Entity, Template, Contentlet, ContentReference, Attribute
11 from philo.utils import fattr
12
13
14 __all__ = ('EntityForm', )
15
16
17 def proxy_fields_for_entity_model(entity_model, fields=None, exclude=None, widgets=None, formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)):
18         field_list = []
19         ignored = []
20         opts = entity_model._entity_meta
21         for f in opts.proxy_fields:
22                 if fields and not f.name in fields:
23                         continue
24                 if exclude and f.name in exclude:
25                         continue
26                 if widgets and f.name in widgets:
27                         kwargs = {'widget': widgets[f.name]}
28                 else:
29                         kwargs = {}
30                 formfield = formfield_callback(f, **kwargs)
31                 if formfield:
32                         field_list.append((f.name, formfield))
33                 else:
34                         ignored.append(f.name)
35         field_dict = SortedDict(field_list)
36         if fields:
37                 field_dict = SortedDict(
38                         [(f, field_dict.get(f)) for f in fields
39                                 if ((not exclude) or (exclude and f not in exclude)) and (f not in ignored) and (f in field_dict)]
40                 )
41         return field_dict
42
43
44 # BEGIN HACK - This will not be required after http://code.djangoproject.com/ticket/14082 has been resolved
45
46 class EntityFormBase(ModelForm):
47         pass
48
49 _old_metaclass_new = ModelFormMetaclass.__new__
50
51 def _new_metaclass_new(cls, name, bases, attrs):
52         new_class = _old_metaclass_new(cls, name, bases, attrs)
53         if issubclass(new_class, EntityFormBase) and new_class._meta.model:
54                 new_class.base_fields.update(proxy_fields_for_entity_model(new_class._meta.model, new_class._meta.fields, new_class._meta.exclude, new_class._meta.widgets)) # don't pass in formfield_callback
55         return new_class
56
57 ModelFormMetaclass.__new__ = staticmethod(_new_metaclass_new)
58
59 # END HACK
60
61
62 class EntityForm(EntityFormBase): # Would inherit from ModelForm directly if it weren't for the above HACK
63         def __init__(self, *args, **kwargs):
64                 initial = kwargs.pop('initial', None)
65                 instance = kwargs.get('instance', None)
66                 if instance is not None:
67                         new_initial = {}
68                         for f in instance._entity_meta.proxy_fields:
69                                 if self._meta.fields and not f.name in self._meta.fields:
70                                         continue
71                                 if self._meta.exclude and f.name in self._meta.exclude:
72                                         continue
73                                 new_initial[f.name] = f.value_from_object(instance)
74                 else:
75                         new_initial = {}
76                 if initial is not None:
77                         new_initial.update(initial)
78                 kwargs['initial'] = new_initial
79                 super(EntityForm, self).__init__(*args, **kwargs)
80         
81         @fattr(alters_data=True)
82         def save(self, commit=True):
83                 cleaned_data = self.cleaned_data
84                 instance = super(EntityForm, self).save(commit=False)
85                 
86                 for f in instance._entity_meta.proxy_fields:
87                         if self._meta.fields and f.name not in self._meta.fields:
88                                 continue
89                         setattr(instance, f.attname, cleaned_data[f.name])
90                 
91                 if commit:
92                         instance.save()
93                         self.save_m2m()
94                 
95                 return instance
96
97
98 class AttributeForm(ModelForm):
99         def __init__(self, *args, **kwargs):
100                 super(AttributeForm, self).__init__(*args, **kwargs)
101                 
102                 # This is necessary because model forms store changes to self.instance in their clean method.
103                 # Mutter mutter.
104                 self._cached_value_ct = self.instance.value_content_type
105                 self._cached_value = self.instance.value
106                 
107                 if self.instance.value is not None:
108                         value_field = self.instance.value.value_formfield()
109                         if value_field:
110                                 self.fields['value'] = value_field
111                         if hasattr(self.instance.value, 'content_type'):
112                                 self.fields['content_type'] = self.instance.value._meta.get_field('content_type').formfield(initial=getattr(self.instance.value.content_type, 'pk', None))
113         
114         def save(self, *args, **kwargs):
115                 # At this point, the cleaned_data has already been stored on self.instance.
116                 if self.instance.value_content_type != self._cached_value_ct:
117                         if self.instance.value is not None:
118                                 self._cached_value.delete()
119                                 if 'value' in self.cleaned_data:
120                                         del(self.cleaned_data['value'])
121                         
122                         if self.instance.value_content_type is not None:
123                                 # Make a blank value of the new type! Run special code for content_type attributes.
124                                 if hasattr(self.instance.value_content_type.model_class(), 'content_type'):
125                                         if self._cached_value and hasattr(self._cached_value, 'content_type'):
126                                                 new_ct = self._cached_value.content_type
127                                         else:
128                                                 new_ct = None
129                                         new_value = self.instance.value_content_type.model_class().objects.create(content_type=new_ct)
130                                 else:
131                                         new_value = self.instance.value_content_type.model_class().objects.create()
132                                 
133                                 new_value.apply_data(self.cleaned_data)
134                                 new_value.save()
135                                 self.instance.value = new_value
136                 else:
137                         # The value type is the same, but one of the fields has changed.
138                         # Check to see if the changed value was the content type. We have to check the
139                         # cleaned_data because self.instance.value.content_type was overridden.
140                         if hasattr(self.instance.value, 'content_type') and 'content_type' in self.cleaned_data and 'value' in self.cleaned_data and (not hasattr(self._cached_value, 'content_type') or self._cached_value.content_type != self.cleaned_data['content_type']):
141                                 self.cleaned_data['value'] = None
142                         
143                         self.instance.value.apply_data(self.cleaned_data)
144                         self.instance.value.save()
145                 
146                 super(AttributeForm, self).save(*args, **kwargs)
147                 return self.instance
148         
149         class Meta:
150                 model = Attribute
151
152
153 class ContainerForm(ModelForm):
154         def __init__(self, *args, **kwargs):
155                 super(ContainerForm, self).__init__(*args, **kwargs)
156                 self.verbose_name = self.instance.name.replace('_', ' ')
157
158
159 class ContentletForm(ContainerForm):
160         content = forms.CharField(required=False, widget=AdminTextareaWidget, label='Content')
161         
162         def should_delete(self):
163                 return not bool(self.cleaned_data['content'])
164         
165         class Meta:
166                 model = Contentlet
167                 fields = ['name', 'content']
168
169
170 class ContentReferenceForm(ContainerForm):
171         def __init__(self, *args, **kwargs):
172                 super(ContentReferenceForm, self).__init__(*args, **kwargs)
173                 try:
174                         self.fields['content_id'].widget = ModelLookupWidget(self.instance.content_type)
175                 except ObjectDoesNotExist:
176                         # This will happen when an empty form (which we will never use) gets instantiated.
177                         pass
178         
179         def should_delete(self):
180                 return (self.cleaned_data['content_id'] is None)
181         
182         class Meta:
183                 model = ContentReference
184                 fields = ['name', 'content_id']
185
186
187 class ContainerInlineFormSet(BaseInlineFormSet):
188         def __init__(self, containers, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
189                 # Unfortunately, I need to add some things to BaseInline between its __init__ and its
190                 # super call, so a lot of this is repetition.
191                 
192                 # Start cribbed from BaseInline
193                 from django.db.models.fields.related import RelatedObject
194                 self.save_as_new = save_as_new
195                 # is there a better way to get the object descriptor?
196                 self.rel_name = RelatedObject(self.fk.rel.to, self.model, self.fk).get_accessor_name()
197                 if self.fk.rel.field_name == self.fk.rel.to._meta.pk.name:
198                         backlink_value = self.instance
199                 else:
200                         backlink_value = getattr(self.instance, self.fk.rel.field_name)
201                 if queryset is None:
202                         queryset = self.model._default_manager
203                 qs = queryset.filter(**{self.fk.name: backlink_value})
204                 # End cribbed from BaseInline
205                 
206                 self.container_instances, qs = self.get_container_instances(containers, qs)
207                 self.extra_containers = containers
208                 self.extra = len(self.extra_containers)
209                 super(BaseInlineFormSet, self).__init__(data, files, prefix=prefix, queryset=qs)
210         
211         def get_container_instances(self, containers, qs):
212                 raise NotImplementedError
213         
214         def total_form_count(self):
215                 if self.data or self.files:
216                         return self.management_form.cleaned_data[TOTAL_FORM_COUNT]
217                 else:
218                         return self.initial_form_count() + self.extra
219         
220         def save_existing_objects(self, commit=True):
221                 self.changed_objects = []
222                 self.deleted_objects = []
223                 if not self.get_queryset():
224                         return []
225
226                 saved_instances = []
227                 for form in self.initial_forms:
228                         pk_name = self._pk_field.name
229                         raw_pk_value = form._raw_value(pk_name)
230
231                         # clean() for different types of PK fields can sometimes return
232                         # the model instance, and sometimes the PK. Handle either.
233                         pk_value = form.fields[pk_name].clean(raw_pk_value)
234                         pk_value = getattr(pk_value, 'pk', pk_value)
235
236                         obj = self._existing_object(pk_value)
237                         if form.should_delete():
238                                 self.deleted_objects.append(obj)
239                                 obj.delete()
240                                 continue
241                         if form.has_changed():
242                                 self.changed_objects.append((obj, form.changed_data))
243                                 saved_instances.append(self.save_existing(form, obj, commit=commit))
244                                 if not commit:
245                                         self.saved_forms.append(form)
246                 return saved_instances
247
248         def save_new_objects(self, commit=True):
249                 self.new_objects = []
250                 for form in self.extra_forms:
251                         if not form.has_changed():
252                                 continue
253                         # If someone has marked an add form for deletion, don't save the
254                         # object.
255                         if form.should_delete():
256                                 continue
257                         self.new_objects.append(self.save_new(form, commit=commit))
258                         if not commit:
259                                 self.saved_forms.append(form)
260                 return self.new_objects
261
262
263 class ContentletInlineFormSet(ContainerInlineFormSet):
264         def __init__(self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
265                 if instance is None:
266                         self.instance = self.fk.rel.to()
267                 else:
268                         self.instance = instance
269                 
270                 try:
271                         containers = list(self.instance.containers[0])
272                 except ObjectDoesNotExist:
273                         containers = []
274         
275                 super(ContentletInlineFormSet, self).__init__(containers, data, files, instance, save_as_new, prefix, queryset)
276         
277         def get_container_instances(self, containers, qs):
278                 qs = qs.filter(name__in=containers)
279                 container_instances = []
280                 for container in qs:
281                         container_instances.append(container)
282                         containers.remove(container.name)
283                 return container_instances, qs
284         
285         def _construct_form(self, i, **kwargs):
286                 if i >= self.initial_form_count(): # and not kwargs.get('instance'):
287                         kwargs['instance'] = self.model(name=self.extra_containers[i - self.initial_form_count() - 1])
288                 
289                 return super(ContentletInlineFormSet, self)._construct_form(i, **kwargs)
290
291
292 class ContentReferenceInlineFormSet(ContainerInlineFormSet):
293         def __init__(self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
294                 if instance is None:
295                         self.instance = self.fk.rel.to()
296                 else:
297                         self.instance = instance
298                 
299                 try:
300                         containers = list(self.instance.containers[1])
301                 except ObjectDoesNotExist:
302                         containers = []
303         
304                 super(ContentReferenceInlineFormSet, self).__init__(containers, data, files, instance, save_as_new, prefix, queryset)
305         
306         def get_container_instances(self, containers, qs):
307                 filter = Q()
308                 
309                 for name, ct in containers:
310                         filter |= Q(name=name, content_type=ct)
311                 
312                 qs = qs.filter(filter)
313                 container_instances = []
314                 for container in qs:
315                         container_instances.append(container)
316                         containers.remove((container.name, container.content_type))
317                 return container_instances, qs
318
319         def _construct_form(self, i, **kwargs):
320                 if i >= self.initial_form_count(): # and not kwargs.get('instance'):
321                         name, content_type = self.extra_containers[i - self.initial_form_count() - 1]
322                         kwargs['instance'] = self.model(name=name, content_type=content_type)
323
324                 return super(ContentReferenceInlineFormSet, self)._construct_form(i, **kwargs)