Added AttributeForm to elegantly handle all the fields that should be displayed in...
[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                 if self.instance.value is not None:
102                         value_field = self.instance.value.value_formfield()
103                         if value_field:
104                                 self.fields['value'] = value_field
105                         if hasattr(self.instance.value, 'content_type'):
106                                 self.fields['content_type'] = self.instance.value._meta.get_field('content_type').formfield(initial=getattr(self.instance.value.content_type, 'pk', None))
107         
108         def save(self, *args, **kwargs):
109                 instance = super(AttributeForm, self).save(*args, **kwargs)
110                 
111                 if self.cleaned_data['value_content_type'] != self.instance.value_content_type:
112                         if self.instance.value is not None:
113                                 self.instance.value.delete()
114                                 del(self.cleaned_data['value'])
115                 elif 'content_type' in self.cleaned_data and self.cleaned_data['content_type'] != self.instance.value.content_type:
116                         self.instance.value.content_type = self.cleaned_data['content_type']
117                         self.instance.value.save()
118                 elif 'value' in self.cleaned_data:
119                         self.instance.set_value(self.cleaned_data['value'])
120                 
121                 return instance
122         
123         class Meta:
124                 model = Attribute
125
126
127 class ContainerForm(ModelForm):
128         def __init__(self, *args, **kwargs):
129                 super(ContainerForm, self).__init__(*args, **kwargs)
130                 self.verbose_name = self.instance.name.replace('_', ' ')
131
132
133 class ContentletForm(ContainerForm):
134         content = forms.CharField(required=False, widget=AdminTextareaWidget, label='Content')
135         
136         def should_delete(self):
137                 return not bool(self.cleaned_data['content'])
138         
139         class Meta:
140                 model = Contentlet
141                 fields = ['name', 'content']
142
143
144 class ContentReferenceForm(ContainerForm):
145         def __init__(self, *args, **kwargs):
146                 super(ContentReferenceForm, self).__init__(*args, **kwargs)
147                 try:
148                         self.fields['content_id'].widget = ModelLookupWidget(self.instance.content_type)
149                 except ObjectDoesNotExist:
150                         # This will happen when an empty form (which we will never use) gets instantiated.
151                         pass
152         
153         def should_delete(self):
154                 return (self.cleaned_data['content_id'] is None)
155         
156         class Meta:
157                 model = ContentReference
158                 fields = ['name', 'content_id']
159
160
161 class ContainerInlineFormSet(BaseInlineFormSet):
162         def __init__(self, containers, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
163                 # Unfortunately, I need to add some things to BaseInline between its __init__ and its
164                 # super call, so a lot of this is repetition.
165                 
166                 # Start cribbed from BaseInline
167                 from django.db.models.fields.related import RelatedObject
168                 self.save_as_new = save_as_new
169                 # is there a better way to get the object descriptor?
170                 self.rel_name = RelatedObject(self.fk.rel.to, self.model, self.fk).get_accessor_name()
171                 if self.fk.rel.field_name == self.fk.rel.to._meta.pk.name:
172                         backlink_value = self.instance
173                 else:
174                         backlink_value = getattr(self.instance, self.fk.rel.field_name)
175                 if queryset is None:
176                         queryset = self.model._default_manager
177                 qs = queryset.filter(**{self.fk.name: backlink_value})
178                 # End cribbed from BaseInline
179                 
180                 self.container_instances, qs = self.get_container_instances(containers, qs)
181                 self.extra_containers = containers
182                 self.extra = len(self.extra_containers)
183                 super(BaseInlineFormSet, self).__init__(data, files, prefix=prefix, queryset=qs)
184         
185         def get_container_instances(self, containers, qs):
186                 raise NotImplementedError
187         
188         def total_form_count(self):
189                 if self.data or self.files:
190                         return self.management_form.cleaned_data[TOTAL_FORM_COUNT]
191                 else:
192                         return self.initial_form_count() + self.extra
193         
194         def save_existing_objects(self, commit=True):
195                 self.changed_objects = []
196                 self.deleted_objects = []
197                 if not self.get_queryset():
198                         return []
199
200                 saved_instances = []
201                 for form in self.initial_forms:
202                         pk_name = self._pk_field.name
203                         raw_pk_value = form._raw_value(pk_name)
204
205                         # clean() for different types of PK fields can sometimes return
206                         # the model instance, and sometimes the PK. Handle either.
207                         pk_value = form.fields[pk_name].clean(raw_pk_value)
208                         pk_value = getattr(pk_value, 'pk', pk_value)
209
210                         obj = self._existing_object(pk_value)
211                         if form.should_delete():
212                                 self.deleted_objects.append(obj)
213                                 obj.delete()
214                                 continue
215                         if form.has_changed():
216                                 self.changed_objects.append((obj, form.changed_data))
217                                 saved_instances.append(self.save_existing(form, obj, commit=commit))
218                                 if not commit:
219                                         self.saved_forms.append(form)
220                 return saved_instances
221
222         def save_new_objects(self, commit=True):
223                 self.new_objects = []
224                 for form in self.extra_forms:
225                         if not form.has_changed():
226                                 continue
227                         # If someone has marked an add form for deletion, don't save the
228                         # object.
229                         if form.should_delete():
230                                 continue
231                         self.new_objects.append(self.save_new(form, commit=commit))
232                         if not commit:
233                                 self.saved_forms.append(form)
234                 return self.new_objects
235
236
237 class ContentletInlineFormSet(ContainerInlineFormSet):
238         def __init__(self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
239                 if instance is None:
240                         self.instance = self.fk.rel.to()
241                 else:
242                         self.instance = instance
243                 
244                 try:
245                         containers = list(self.instance.containers[0])
246                 except ObjectDoesNotExist:
247                         containers = []
248         
249                 super(ContentletInlineFormSet, self).__init__(containers, data, files, instance, save_as_new, prefix, queryset)
250         
251         def get_container_instances(self, containers, qs):
252                 qs = qs.filter(name__in=containers)
253                 container_instances = []
254                 for container in qs:
255                         container_instances.append(container)
256                         containers.remove(container.name)
257                 return container_instances, qs
258         
259         def _construct_form(self, i, **kwargs):
260                 if i >= self.initial_form_count(): # and not kwargs.get('instance'):
261                         kwargs['instance'] = self.model(name=self.extra_containers[i - self.initial_form_count() - 1])
262                 
263                 return super(ContentletInlineFormSet, self)._construct_form(i, **kwargs)
264
265
266 class ContentReferenceInlineFormSet(ContainerInlineFormSet):
267         def __init__(self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
268                 if instance is None:
269                         self.instance = self.fk.rel.to()
270                 else:
271                         self.instance = instance
272                 
273                 try:
274                         containers = list(self.instance.containers[1])
275                 except ObjectDoesNotExist:
276                         containers = []
277         
278                 super(ContentReferenceInlineFormSet, self).__init__(containers, data, files, instance, save_as_new, prefix, queryset)
279         
280         def get_container_instances(self, containers, qs):
281                 filter = Q()
282                 
283                 for name, ct in containers:
284                         filter |= Q(name=name, content_type=ct)
285                 
286                 qs = qs.filter(filter)
287                 container_instances = []
288                 for container in qs:
289                         container_instances.append(container)
290                         containers.remove((container.name, container.content_type))
291                 return container_instances, qs
292
293         def _construct_form(self, i, **kwargs):
294                 if i >= self.initial_form_count(): # and not kwargs.get('instance'):
295                         name, content_type = self.extra_containers[i - self.initial_form_count() - 1]
296                         kwargs['instance'] = self.model(name=name, content_type=content_type)
297
298                 return super(ContentReferenceInlineFormSet, self)._construct_form(i, **kwargs)