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