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
16 __all__ = ('EntityForm', )
19 def proxy_fields_for_entity_model(entity_model, fields=None, exclude=None, widgets=None, formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)):
22 opts = entity_model._entity_meta
23 for f in opts.proxy_fields:
26 if fields and not f.name in fields:
28 if exclude and f.name in exclude:
30 if widgets and f.name in widgets:
31 kwargs = {'widget': widgets[f.name]}
34 formfield = formfield_callback(f, **kwargs)
36 field_list.append((f.name, formfield))
38 ignored.append(f.name)
39 field_dict = SortedDict(field_list)
41 field_dict = SortedDict(
42 [(f, field_dict.get(f)) for f in fields
43 if ((not exclude) or (exclude and f not in exclude)) and (f not in ignored) and (f in field_dict)]
48 # BEGIN HACK - This will not be required after http://code.djangoproject.com/ticket/14082 has been resolved
50 class EntityFormBase(ModelForm):
53 _old_metaclass_new = ModelFormMetaclass.__new__
55 def _new_metaclass_new(cls, name, bases, attrs):
56 new_class = _old_metaclass_new(cls, name, bases, attrs)
57 if issubclass(new_class, EntityFormBase) and new_class._meta.model:
58 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
61 ModelFormMetaclass.__new__ = staticmethod(_new_metaclass_new)
66 class EntityForm(EntityFormBase): # Would inherit from ModelForm directly if it weren't for the above HACK
67 def __init__(self, *args, **kwargs):
68 initial = kwargs.pop('initial', None)
69 instance = kwargs.get('instance', None)
70 if instance is not None:
72 for f in instance._entity_meta.proxy_fields:
73 if self._meta.fields and not f.name in self._meta.fields:
75 if self._meta.exclude and f.name in self._meta.exclude:
77 new_initial[f.name] = f.value_from_object(instance)
80 if initial is not None:
81 new_initial.update(initial)
82 kwargs['initial'] = new_initial
83 super(EntityForm, self).__init__(*args, **kwargs)
85 @fattr(alters_data=True)
86 def save(self, commit=True):
87 cleaned_data = self.cleaned_data
88 instance = super(EntityForm, self).save(commit=False)
90 for f in instance._entity_meta.proxy_fields:
91 if not f.editable or not f.name in cleaned_data:
93 if self._meta.fields and f.name not in self._meta.fields:
95 if self._meta.exclude and f.name in self._meta.exclude:
97 setattr(instance, f.attname, cleaned_data[f.name])
106 class AttributeForm(ModelForm):
107 def __init__(self, *args, **kwargs):
108 super(AttributeForm, self).__init__(*args, **kwargs)
110 # This is necessary because model forms store changes to self.instance in their clean method.
112 self._cached_value_ct = self.instance.value_content_type
113 self._cached_value = self.instance.value
115 if self.instance.value is not None:
116 value_field = self.instance.value.value_formfield()
118 self.fields['value'] = value_field
119 if hasattr(self.instance.value, 'content_type'):
120 self.fields['content_type'] = self.instance.value._meta.get_field('content_type').formfield(initial=getattr(self.instance.value.content_type, 'pk', None))
122 def save(self, *args, **kwargs):
123 # At this point, the cleaned_data has already been stored on self.instance.
124 if self.instance.value_content_type != self._cached_value_ct:
125 if self.instance.value is not None:
126 self._cached_value.delete()
127 if 'value' in self.cleaned_data:
128 del(self.cleaned_data['value'])
130 if self.instance.value_content_type is not None:
131 # Make a blank value of the new type! Run special code for content_type attributes.
132 if hasattr(self.instance.value_content_type.model_class(), 'content_type'):
133 if self._cached_value and hasattr(self._cached_value, 'content_type'):
134 new_ct = self._cached_value.content_type
137 new_value = self.instance.value_content_type.model_class().objects.create(content_type=new_ct)
139 new_value = self.instance.value_content_type.model_class().objects.create()
141 new_value.apply_data(self.cleaned_data)
143 self.instance.value = new_value
145 # The value type is the same, but one of the fields has changed.
146 # Check to see if the changed value was the content type. We have to check the
147 # cleaned_data because self.instance.value.content_type was overridden.
148 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']):
149 self.cleaned_data['value'] = None
151 self.instance.value.apply_data(self.cleaned_data)
152 self.instance.value.save()
154 super(AttributeForm, self).save(*args, **kwargs)
161 class AttributeInlineFormSet(BaseGenericInlineFormSet):
162 "Necessary to force the GenericInlineFormset to use the form's save method for new objects."
163 def save_new(self, form, commit):
164 setattr(form.instance, self.ct_field.get_attname(), ContentType.objects.get_for_model(self.instance).pk)
165 setattr(form.instance, self.ct_fk_field.get_attname(), self.instance.pk)
169 class ContainerForm(ModelForm):
170 def __init__(self, *args, **kwargs):
171 super(ContainerForm, self).__init__(*args, **kwargs)
172 self.verbose_name = self.instance.name.replace('_', ' ')
175 class ContentletForm(ContainerForm):
176 content = forms.CharField(required=False, widget=AdminTextareaWidget, label='Content')
178 def should_delete(self):
179 return not bool(self.cleaned_data['content'])
183 fields = ['name', 'content']
186 class ContentReferenceForm(ContainerForm):
187 def __init__(self, *args, **kwargs):
188 super(ContentReferenceForm, self).__init__(*args, **kwargs)
190 self.fields['content_id'].widget = ModelLookupWidget(self.instance.content_type)
191 except ObjectDoesNotExist:
192 # This will happen when an empty form (which we will never use) gets instantiated.
195 def should_delete(self):
196 return (self.cleaned_data['content_id'] is None)
199 model = ContentReference
200 fields = ['name', 'content_id']
203 class ContainerInlineFormSet(BaseInlineFormSet):
204 def __init__(self, containers, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
205 # Unfortunately, I need to add some things to BaseInline between its __init__ and its
206 # super call, so a lot of this is repetition.
208 # Start cribbed from BaseInline
209 from django.db.models.fields.related import RelatedObject
210 self.save_as_new = save_as_new
211 # is there a better way to get the object descriptor?
212 self.rel_name = RelatedObject(self.fk.rel.to, self.model, self.fk).get_accessor_name()
213 if self.fk.rel.field_name == self.fk.rel.to._meta.pk.name:
214 backlink_value = self.instance
216 backlink_value = getattr(self.instance, self.fk.rel.field_name)
218 queryset = self.model._default_manager
219 qs = queryset.filter(**{self.fk.name: backlink_value})
220 # End cribbed from BaseInline
222 self.container_instances, qs = self.get_container_instances(containers, qs)
223 self.extra_containers = containers
224 self.extra = len(self.extra_containers)
225 super(BaseInlineFormSet, self).__init__(data, files, prefix=prefix, queryset=qs)
227 def get_container_instances(self, containers, qs):
228 raise NotImplementedError
230 def total_form_count(self):
231 if self.data or self.files:
232 return self.management_form.cleaned_data[TOTAL_FORM_COUNT]
234 return self.initial_form_count() + self.extra
236 def save_existing_objects(self, commit=True):
237 self.changed_objects = []
238 self.deleted_objects = []
239 if not self.get_queryset():
243 for form in self.initial_forms:
244 pk_name = self._pk_field.name
245 raw_pk_value = form._raw_value(pk_name)
247 # clean() for different types of PK fields can sometimes return
248 # the model instance, and sometimes the PK. Handle either.
249 pk_value = form.fields[pk_name].clean(raw_pk_value)
250 pk_value = getattr(pk_value, 'pk', pk_value)
252 obj = self._existing_object(pk_value)
253 if form.should_delete():
254 self.deleted_objects.append(obj)
257 if form.has_changed():
258 self.changed_objects.append((obj, form.changed_data))
259 saved_instances.append(self.save_existing(form, obj, commit=commit))
261 self.saved_forms.append(form)
262 return saved_instances
264 def save_new_objects(self, commit=True):
265 self.new_objects = []
266 for form in self.extra_forms:
267 if not form.has_changed():
269 # If someone has marked an add form for deletion, don't save the
271 if form.should_delete():
273 self.new_objects.append(self.save_new(form, commit=commit))
275 self.saved_forms.append(form)
276 return self.new_objects
279 class ContentletInlineFormSet(ContainerInlineFormSet):
280 def __init__(self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
282 self.instance = self.fk.rel.to()
284 self.instance = instance
287 containers = list(self.instance.containers[0])
288 except ObjectDoesNotExist:
291 super(ContentletInlineFormSet, self).__init__(containers, data, files, instance, save_as_new, prefix, queryset)
293 def get_container_instances(self, containers, qs):
294 qs = qs.filter(name__in=containers)
295 container_instances = []
297 container_instances.append(container)
298 containers.remove(container.name)
299 return container_instances, qs
301 def _construct_form(self, i, **kwargs):
302 if i >= self.initial_form_count(): # and not kwargs.get('instance'):
303 kwargs['instance'] = self.model(name=self.extra_containers[i - self.initial_form_count() - 1])
305 return super(ContentletInlineFormSet, self)._construct_form(i, **kwargs)
308 class ContentReferenceInlineFormSet(ContainerInlineFormSet):
309 def __init__(self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
311 self.instance = self.fk.rel.to()
313 self.instance = instance
316 containers = list(self.instance.containers[1])
317 except ObjectDoesNotExist:
320 super(ContentReferenceInlineFormSet, self).__init__(containers, data, files, instance, save_as_new, prefix, queryset)
322 def get_container_instances(self, containers, qs):
325 for name, ct in containers:
326 filter |= Q(name=name, content_type=ct)
328 qs = qs.filter(filter)
329 container_instances = []
331 container_instances.append(container)
332 containers.remove((container.name, container.content_type))
333 return container_instances, qs
335 def _construct_form(self, i, **kwargs):
336 if i >= self.initial_form_count(): # and not kwargs.get('instance'):
337 name, content_type = self.extra_containers[i - self.initial_form_count() - 1]
338 kwargs['instance'] = self.model(name=name, content_type=content_type)
340 return super(ContentReferenceInlineFormSet, self)._construct_form(i, **kwargs)