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.models.fields import RelationshipField
12 from philo.utils import fattr
15 __all__ = ('EntityForm', )
18 def proxy_fields_for_entity_model(entity_model, fields=None, exclude=None, widgets=None, formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)):
21 opts = entity_model._entity_meta
22 for f in opts.proxy_fields:
23 if fields and not f.name in fields:
25 if exclude and f.name in exclude:
27 if widgets and f.name in widgets:
28 kwargs = {'widget': widgets[f.name]}
31 formfield = formfield_callback(f, **kwargs)
33 field_list.append((f.name, formfield))
35 ignored.append(f.name)
36 field_dict = SortedDict(field_list)
38 field_dict = SortedDict(
39 [(f, field_dict.get(f)) for f in fields
40 if ((not exclude) or (exclude and f not in exclude)) and (f not in ignored) and (f in field_dict)]
45 # BEGIN HACK - This will not be required after http://code.djangoproject.com/ticket/14082 has been resolved
47 class EntityFormBase(ModelForm):
50 _old_metaclass_new = ModelFormMetaclass.__new__
52 def _new_metaclass_new(cls, name, bases, attrs):
53 new_class = _old_metaclass_new(cls, name, bases, attrs)
54 if issubclass(new_class, EntityFormBase) and new_class._meta.model:
55 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
58 ModelFormMetaclass.__new__ = staticmethod(_new_metaclass_new)
63 class EntityForm(EntityFormBase): # Would inherit from ModelForm directly if it weren't for the above HACK
64 def __init__(self, *args, **kwargs):
65 initial = kwargs.pop('initial', None)
66 instance = kwargs.get('instance', None)
67 if instance is not None:
69 for f in instance._entity_meta.proxy_fields:
70 if self._meta.fields and not f.name in self._meta.fields:
72 if self._meta.exclude and f.name in self._meta.exclude:
74 new_initial[f.name] = f.value_from_object(instance)
77 if initial is not None:
78 new_initial.update(initial)
79 kwargs['initial'] = new_initial
80 super(EntityForm, self).__init__(*args, **kwargs)
82 @fattr(alters_data=True)
83 def save(self, commit=True):
84 cleaned_data = self.cleaned_data
85 instance = super(EntityForm, self).save(commit=False)
87 for f in instance._entity_meta.proxy_fields:
88 if self._meta.fields and f.name not in self._meta.fields:
90 setattr(instance, f.attname, cleaned_data[f.name])
99 def validate_template(template):
101 Makes sure that the template and all included or extended templates are valid.
103 for node in template.nodelist:
105 if isinstance(node, loader_tags.ExtendsNode):
106 extended_template = node.get_parent(Context())
107 validate_template(extended_template)
108 elif isinstance(node, loader_tags.IncludeNode):
109 included_template = loader.get_template(node.template_name.resolve(Context()))
110 validate_template(extended_template)
112 raise ValidationError("Template code invalid. Error was: %s: %s" % (e.__class__.__name__, e))
115 class TemplateForm(ModelForm):
116 def clean_code(self):
117 code = self.cleaned_data['code']
119 t = DjangoTemplate(code)
121 raise ValidationError("Template code invalid. Error was: %s: %s" % (e.__class__.__name__, e))
130 class ContainerForm(ModelForm):
131 def __init__(self, *args, **kwargs):
132 super(ContainerForm, self).__init__(*args, **kwargs)
133 self.verbose_name = self.instance.name.replace('_', ' ')
136 class ContentletForm(ContainerForm):
137 content = forms.CharField(required=False, widget=AdminTextareaWidget)
139 def should_delete(self):
140 return not bool(self.cleaned_data['content'])
144 fields = ['name', 'content', 'dynamic']
147 class ContentReferenceForm(ContainerForm):
148 def __init__(self, *args, **kwargs):
149 super(ContentReferenceForm, self).__init__(*args, **kwargs)
151 self.fields['content_id'].widget = ModelLookupWidget(self.instance.content_type)
152 except ObjectDoesNotExist:
153 # This will happen when an empty form (which we will never use) gets instantiated.
156 def should_delete(self):
157 return (self.cleaned_data['content_id'] is None)
160 model = ContentReference
161 fields = ['name', 'content_id']
164 class ContainerInlineFormSet(BaseInlineFormSet):
165 def __init__(self, containers, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
166 # Unfortunately, I need to add some things to BaseInline between its __init__ and its super call, so
167 # a lot of this is repetition.
169 # Start cribbed from BaseInline
170 from django.db.models.fields.related import RelatedObject
171 self.save_as_new = save_as_new
172 # is there a better way to get the object descriptor?
173 self.rel_name = RelatedObject(self.fk.rel.to, self.model, self.fk).get_accessor_name()
174 if self.fk.rel.field_name == self.fk.rel.to._meta.pk.name:
175 backlink_value = self.instance
177 backlink_value = getattr(self.instance, self.fk.rel.field_name)
179 queryset = self.model._default_manager
180 qs = queryset.filter(**{self.fk.name: backlink_value})
181 # End cribbed from BaseInline
183 self.container_instances, qs = self.get_container_instances(containers, qs)
184 self.extra_containers = containers
185 self.extra = len(self.extra_containers)
186 super(BaseInlineFormSet, self).__init__(data, files, prefix=prefix, queryset=qs)
188 def get_container_instances(self, containers, qs):
189 raise NotImplementedError
191 def total_form_count(self):
192 if self.data or self.files:
193 return self.management_form.cleaned_data[TOTAL_FORM_COUNT]
195 return self.initial_form_count() + self.extra
197 def save_existing_objects(self, commit=True):
198 self.changed_objects = []
199 self.deleted_objects = []
200 if not self.get_queryset():
204 for form in self.initial_forms:
205 pk_name = self._pk_field.name
206 raw_pk_value = form._raw_value(pk_name)
208 # clean() for different types of PK fields can sometimes return
209 # the model instance, and sometimes the PK. Handle either.
210 pk_value = form.fields[pk_name].clean(raw_pk_value)
211 pk_value = getattr(pk_value, 'pk', pk_value)
213 obj = self._existing_object(pk_value)
214 if form.should_delete():
215 self.deleted_objects.append(obj)
218 if form.has_changed():
219 self.changed_objects.append((obj, form.changed_data))
220 saved_instances.append(self.save_existing(form, obj, commit=commit))
222 self.saved_forms.append(form)
223 return saved_instances
225 def save_new_objects(self, commit=True):
226 self.new_objects = []
227 for form in self.extra_forms:
228 if not form.has_changed():
230 # If someone has marked an add form for deletion, don't save the
232 if form.should_delete():
234 self.new_objects.append(self.save_new(form, commit=commit))
236 self.saved_forms.append(form)
237 return self.new_objects
240 class ContentletInlineFormSet(ContainerInlineFormSet):
241 def __init__(self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
243 self.instance = self.fk.rel.to()
245 self.instance = instance
248 containers = list(self.instance.containers[0])
249 except ObjectDoesNotExist:
252 super(ContentletInlineFormSet, self).__init__(containers, data, files, instance, save_as_new, prefix, queryset)
254 def get_container_instances(self, containers, qs):
255 qs = qs.filter(name__in=containers)
256 container_instances = []
258 container_instances.append(container)
259 containers.remove(container.name)
260 return container_instances, qs
262 def _construct_form(self, i, **kwargs):
263 if i >= self.initial_form_count(): # and not kwargs.get('instance'):
264 kwargs['instance'] = self.model(name=self.extra_containers[i - self.initial_form_count() - 1])
266 return super(ContentletInlineFormSet, self)._construct_form(i, **kwargs)
269 class ContentReferenceInlineFormSet(ContainerInlineFormSet):
270 def __init__(self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
272 self.instance = self.fk.rel.to()
274 self.instance = instance
277 containers = list(self.instance.containers[1])
278 except ObjectDoesNotExist:
281 super(ContentReferenceInlineFormSet, self).__init__(containers, data, files, instance, save_as_new, prefix, queryset)
283 def get_container_instances(self, containers, qs):
286 for name, ct in containers:
287 filter |= Q(name=name, content_type=ct)
289 qs = qs.filter(filter)
290 container_instances = []
292 container_instances.append(container)
293 containers.remove((container.name, container.content_type))
294 return container_instances, qs
296 def _construct_form(self, i, **kwargs):
297 if i >= self.initial_form_count(): # and not kwargs.get('instance'):
298 name, content_type = self.extra_containers[i - self.initial_form_count() - 1]
299 kwargs['instance'] = self.model(name=name, content_type=content_type)
301 return super(ContentReferenceInlineFormSet, self)._construct_form(i, **kwargs)