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:
24 if fields and not f.name in fields:
26 if exclude and f.name in exclude:
28 if widgets and f.name in widgets:
29 kwargs = {'widget': widgets[f.name]}
32 formfield = formfield_callback(f, **kwargs)
34 field_list.append((f.name, formfield))
36 ignored.append(f.name)
37 field_dict = SortedDict(field_list)
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)]
46 # BEGIN HACK - This will not be required after http://code.djangoproject.com/ticket/14082 has been resolved
48 class EntityFormBase(ModelForm):
51 _old_metaclass_new = ModelFormMetaclass.__new__
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
59 ModelFormMetaclass.__new__ = staticmethod(_new_metaclass_new)
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:
70 for f in instance._entity_meta.proxy_fields:
71 if self._meta.fields and not f.name in self._meta.fields:
73 if self._meta.exclude and f.name in self._meta.exclude:
75 new_initial[f.name] = f.value_from_object(instance)
78 if initial is not None:
79 new_initial.update(initial)
80 kwargs['initial'] = new_initial
81 super(EntityForm, self).__init__(*args, **kwargs)
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)
88 for f in instance._entity_meta.proxy_fields:
89 if self._meta.fields and f.name not in self._meta.fields:
91 setattr(instance, f.attname, cleaned_data[f.name])
100 class AttributeForm(ModelForm):
101 def __init__(self, *args, **kwargs):
102 super(AttributeForm, self).__init__(*args, **kwargs)
104 # This is necessary because model forms store changes to self.instance in their clean method.
106 self._cached_value_ct = self.instance.value_content_type
107 self._cached_value = self.instance.value
109 if self.instance.value is not None:
110 value_field = self.instance.value.value_formfield()
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))
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'])
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
131 new_value = self.instance.value_content_type.model_class().objects.create(content_type=new_ct)
133 new_value = self.instance.value_content_type.model_class().objects.create()
135 new_value.apply_data(self.cleaned_data)
137 self.instance.value = new_value
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
145 self.instance.value.apply_data(self.cleaned_data)
146 self.instance.value.save()
148 super(AttributeForm, self).save(*args, **kwargs)
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)
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('_', ' ')
169 class ContentletForm(ContainerForm):
170 content = forms.CharField(required=False, widget=AdminTextareaWidget, label='Content')
172 def should_delete(self):
173 return not bool(self.cleaned_data['content'])
177 fields = ['name', 'content']
180 class ContentReferenceForm(ContainerForm):
181 def __init__(self, *args, **kwargs):
182 super(ContentReferenceForm, self).__init__(*args, **kwargs)
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.
189 def should_delete(self):
190 return (self.cleaned_data['content_id'] is None)
193 model = ContentReference
194 fields = ['name', 'content_id']
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.
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
210 backlink_value = getattr(self.instance, self.fk.rel.field_name)
212 queryset = self.model._default_manager
213 qs = queryset.filter(**{self.fk.name: backlink_value})
214 # End cribbed from BaseInline
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)
221 def get_container_instances(self, containers, qs):
222 raise NotImplementedError
224 def total_form_count(self):
225 if self.data or self.files:
226 return self.management_form.cleaned_data[TOTAL_FORM_COUNT]
228 return self.initial_form_count() + self.extra
230 def save_existing_objects(self, commit=True):
231 self.changed_objects = []
232 self.deleted_objects = []
233 if not self.get_queryset():
237 for form in self.initial_forms:
238 pk_name = self._pk_field.name
239 raw_pk_value = form._raw_value(pk_name)
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)
246 obj = self._existing_object(pk_value)
247 if form.should_delete():
248 self.deleted_objects.append(obj)
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))
255 self.saved_forms.append(form)
256 return saved_instances
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():
263 # If someone has marked an add form for deletion, don't save the
265 if form.should_delete():
267 self.new_objects.append(self.save_new(form, commit=commit))
269 self.saved_forms.append(form)
270 return self.new_objects
273 class ContentletInlineFormSet(ContainerInlineFormSet):
274 def __init__(self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
276 self.instance = self.fk.rel.to()
278 self.instance = instance
281 containers = list(self.instance.containers[0])
282 except ObjectDoesNotExist:
285 super(ContentletInlineFormSet, self).__init__(containers, data, files, instance, save_as_new, prefix, queryset)
287 def get_container_instances(self, containers, qs):
288 qs = qs.filter(name__in=containers)
289 container_instances = []
291 container_instances.append(container)
292 containers.remove(container.name)
293 return container_instances, qs
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])
299 return super(ContentletInlineFormSet, self)._construct_form(i, **kwargs)
302 class ContentReferenceInlineFormSet(ContainerInlineFormSet):
303 def __init__(self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
305 self.instance = self.fk.rel.to()
307 self.instance = instance
310 containers = list(self.instance.containers[1])
311 except ObjectDoesNotExist:
314 super(ContentReferenceInlineFormSet, self).__init__(containers, data, files, instance, save_as_new, prefix, queryset)
316 def get_container_instances(self, containers, qs):
319 for name, ct in containers:
320 filter |= Q(name=name, content_type=ct)
322 qs = qs.filter(filter)
323 container_instances = []
325 container_instances.append(container)
326 containers.remove((container.name, container.content_type))
327 return container_instances, qs
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)
334 return super(ContentReferenceInlineFormSet, self)._construct_form(i, **kwargs)