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
11 from philo.utils import fattr
14 __all__ = ('EntityForm', )
17 def proxy_fields_for_entity_model(entity_model, fields=None, exclude=None, widgets=None, formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)):
20 opts = entity_model._entity_meta
21 for f in opts.proxy_fields:
22 if fields and not f.name in fields:
24 if exclude and f.name in exclude:
26 if widgets and f.name in widgets:
27 kwargs = {'widget': widgets[f.name]}
30 formfield = formfield_callback(f, **kwargs)
32 field_list.append((f.name, formfield))
34 ignored.append(f.name)
35 field_dict = SortedDict(field_list)
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)]
44 # BEGIN HACK - This will not be required after http://code.djangoproject.com/ticket/14082 has been resolved
46 class EntityFormBase(ModelForm):
49 _old_metaclass_new = ModelFormMetaclass.__new__
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
57 ModelFormMetaclass.__new__ = staticmethod(_new_metaclass_new)
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:
68 for f in instance._entity_meta.proxy_fields:
69 if self._meta.fields and not f.name in self._meta.fields:
71 if self._meta.exclude and f.name in self._meta.exclude:
73 new_initial[f.name] = f.value_from_object(instance)
76 if initial is not None:
77 new_initial.update(initial)
78 kwargs['initial'] = new_initial
79 super(EntityForm, self).__init__(*args, **kwargs)
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)
86 for f in instance._entity_meta.proxy_fields:
87 if self._meta.fields and f.name not in self._meta.fields:
89 setattr(instance, f.attname, cleaned_data[f.name])
98 class ContainerForm(ModelForm):
99 def __init__(self, *args, **kwargs):
100 super(ContainerForm, self).__init__(*args, **kwargs)
101 self.verbose_name = self.instance.name.replace('_', ' ')
104 class ContentletForm(ContainerForm):
105 content = forms.CharField(required=False, widget=AdminTextareaWidget, label='Content')
107 def should_delete(self):
108 return not bool(self.cleaned_data['content'])
112 fields = ['name', 'content']
115 class ContentReferenceForm(ContainerForm):
116 def __init__(self, *args, **kwargs):
117 super(ContentReferenceForm, self).__init__(*args, **kwargs)
119 self.fields['content_id'].widget = ModelLookupWidget(self.instance.content_type)
120 except ObjectDoesNotExist:
121 # This will happen when an empty form (which we will never use) gets instantiated.
124 def should_delete(self):
125 return (self.cleaned_data['content_id'] is None)
128 model = ContentReference
129 fields = ['name', 'content_id']
132 class ContainerInlineFormSet(BaseInlineFormSet):
133 def __init__(self, containers, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
134 # Unfortunately, I need to add some things to BaseInline between its __init__ and its
135 # super call, so a lot of this is repetition.
137 # Start cribbed from BaseInline
138 from django.db.models.fields.related import RelatedObject
139 self.save_as_new = save_as_new
140 # is there a better way to get the object descriptor?
141 self.rel_name = RelatedObject(self.fk.rel.to, self.model, self.fk).get_accessor_name()
142 if self.fk.rel.field_name == self.fk.rel.to._meta.pk.name:
143 backlink_value = self.instance
145 backlink_value = getattr(self.instance, self.fk.rel.field_name)
147 queryset = self.model._default_manager
148 qs = queryset.filter(**{self.fk.name: backlink_value})
149 # End cribbed from BaseInline
151 self.container_instances, qs = self.get_container_instances(containers, qs)
152 self.extra_containers = containers
153 self.extra = len(self.extra_containers)
154 super(BaseInlineFormSet, self).__init__(data, files, prefix=prefix, queryset=qs)
156 def get_container_instances(self, containers, qs):
157 raise NotImplementedError
159 def total_form_count(self):
160 if self.data or self.files:
161 return self.management_form.cleaned_data[TOTAL_FORM_COUNT]
163 return self.initial_form_count() + self.extra
165 def save_existing_objects(self, commit=True):
166 self.changed_objects = []
167 self.deleted_objects = []
168 if not self.get_queryset():
172 for form in self.initial_forms:
173 pk_name = self._pk_field.name
174 raw_pk_value = form._raw_value(pk_name)
176 # clean() for different types of PK fields can sometimes return
177 # the model instance, and sometimes the PK. Handle either.
178 pk_value = form.fields[pk_name].clean(raw_pk_value)
179 pk_value = getattr(pk_value, 'pk', pk_value)
181 obj = self._existing_object(pk_value)
182 if form.should_delete():
183 self.deleted_objects.append(obj)
186 if form.has_changed():
187 self.changed_objects.append((obj, form.changed_data))
188 saved_instances.append(self.save_existing(form, obj, commit=commit))
190 self.saved_forms.append(form)
191 return saved_instances
193 def save_new_objects(self, commit=True):
194 self.new_objects = []
195 for form in self.extra_forms:
196 if not form.has_changed():
198 # If someone has marked an add form for deletion, don't save the
200 if form.should_delete():
202 self.new_objects.append(self.save_new(form, commit=commit))
204 self.saved_forms.append(form)
205 return self.new_objects
208 class ContentletInlineFormSet(ContainerInlineFormSet):
209 def __init__(self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
211 self.instance = self.fk.rel.to()
213 self.instance = instance
216 containers = list(self.instance.containers[0])
217 except ObjectDoesNotExist:
220 super(ContentletInlineFormSet, self).__init__(containers, data, files, instance, save_as_new, prefix, queryset)
222 def get_container_instances(self, containers, qs):
223 qs = qs.filter(name__in=containers)
224 container_instances = []
226 container_instances.append(container)
227 containers.remove(container.name)
228 return container_instances, qs
230 def _construct_form(self, i, **kwargs):
231 if i >= self.initial_form_count(): # and not kwargs.get('instance'):
232 kwargs['instance'] = self.model(name=self.extra_containers[i - self.initial_form_count() - 1])
234 return super(ContentletInlineFormSet, self)._construct_form(i, **kwargs)
237 class ContentReferenceInlineFormSet(ContainerInlineFormSet):
238 def __init__(self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
240 self.instance = self.fk.rel.to()
242 self.instance = instance
245 containers = list(self.instance.containers[1])
246 except ObjectDoesNotExist:
249 super(ContentReferenceInlineFormSet, self).__init__(containers, data, files, instance, save_as_new, prefix, queryset)
251 def get_container_instances(self, containers, qs):
254 for name, ct in containers:
255 filter |= Q(name=name, content_type=ct)
257 qs = qs.filter(filter)
258 container_instances = []
260 container_instances.append(container)
261 containers.remove((container.name, container.content_type))
262 return container_instances, qs
264 def _construct_form(self, i, **kwargs):
265 if i >= self.initial_form_count(): # and not kwargs.get('instance'):
266 name, content_type = self.extra_containers[i - self.initial_form_count() - 1]
267 kwargs['instance'] = self.model(name=name, content_type=content_type)
269 return super(ContentReferenceInlineFormSet, self)._construct_form(i, **kwargs)