Merge branch 'master' of git://github.com/melinath/philo
[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
11 from philo.models.fields import RelationshipField
12 from philo.utils import fattr
13
14
15 __all__ = ('EntityForm', )
16
17
18 def proxy_fields_for_entity_model(entity_model, fields=None, exclude=None, widgets=None, formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)):
19         field_list = []
20         ignored = []
21         opts = entity_model._entity_meta
22         for f in opts.proxy_fields:
23                 if fields and not f.name in fields:
24                         continue
25                 if exclude and f.name in exclude:
26                         continue
27                 if widgets and f.name in widgets:
28                         kwargs = {'widget': widgets[f.name]}
29                 else:
30                         kwargs = {}
31                 formfield = formfield_callback(f, **kwargs)
32                 if formfield:
33                         field_list.append((f.name, formfield))
34                 else:
35                         ignored.append(f.name)
36         field_dict = SortedDict(field_list)
37         if fields:
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)]
41                 )
42         return field_dict
43
44
45 # BEGIN HACK - This will not be required after http://code.djangoproject.com/ticket/14082 has been resolved
46
47 class EntityFormBase(ModelForm):
48         pass
49
50 _old_metaclass_new = ModelFormMetaclass.__new__
51
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
56         return new_class
57
58 ModelFormMetaclass.__new__ = staticmethod(_new_metaclass_new)
59
60 # END HACK
61
62
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:
68                         new_initial = {}
69                         for f in instance._entity_meta.proxy_fields:
70                                 if self._meta.fields and not f.name in self._meta.fields:
71                                         continue
72                                 if self._meta.exclude and f.name in self._meta.exclude:
73                                         continue
74                                 new_initial[f.name] = f.value_from_object(instance)
75                 else:
76                         new_initial = {}
77                 if initial is not None:
78                         new_initial.update(initial)
79                 kwargs['initial'] = new_initial
80                 super(EntityForm, self).__init__(*args, **kwargs)
81         
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)
86                 
87                 for f in instance._entity_meta.proxy_fields:
88                         if self._meta.fields and f.name not in self._meta.fields:
89                                 continue
90                         setattr(instance, f.attname, cleaned_data[f.name])
91                 
92                 if commit:
93                         instance.save()
94                         self.save_m2m()
95                 
96                 return instance
97
98
99 def validate_template(template):
100         """
101         Makes sure that the template and all included or extended templates are valid.
102         """ 
103         for node in template.nodelist:
104                 try:
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)
111                 except Exception, e:
112                         raise ValidationError("Template code invalid. Error was: %s: %s" % (e.__class__.__name__, e))
113
114
115 class TemplateForm(ModelForm):
116         def clean_code(self):
117                 code = self.cleaned_data['code']
118                 try:
119                         t = DjangoTemplate(code)
120                 except Exception, e:
121                         raise ValidationError("Template code invalid. Error was: %s: %s" % (e.__class__.__name__, e))
122
123                 validate_template(t)
124                 return code
125
126         class Meta:
127                 model = Template
128
129
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('_', ' ')
134
135
136 class ContentletForm(ContainerForm):
137         content = forms.CharField(required=False, widget=AdminTextareaWidget)
138         
139         def should_delete(self):
140                 return not bool(self.cleaned_data['content'])
141         
142         class Meta:
143                 model = Contentlet
144                 fields = ['name', 'content', 'dynamic']
145
146
147 class ContentReferenceForm(ContainerForm):
148         def __init__(self, *args, **kwargs):
149                 super(ContentReferenceForm, self).__init__(*args, **kwargs)
150                 try:
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.
154                         pass
155         
156         def should_delete(self):
157                 return (self.cleaned_data['content_id'] is None)
158         
159         class Meta:
160                 model = ContentReference
161                 fields = ['name', 'content_id']
162
163
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.
168                 
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
176                 else:
177                         backlink_value = getattr(self.instance, self.fk.rel.field_name)
178                 if queryset is None:
179                         queryset = self.model._default_manager
180                 qs = queryset.filter(**{self.fk.name: backlink_value})
181                 # End cribbed from BaseInline
182                 
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)
187         
188         def get_container_instances(self, containers, qs):
189                 raise NotImplementedError
190         
191         def total_form_count(self):
192                 if self.data or self.files:
193                         return self.management_form.cleaned_data[TOTAL_FORM_COUNT]
194                 else:
195                         return self.initial_form_count() + self.extra
196         
197         def save_existing_objects(self, commit=True):
198                 self.changed_objects = []
199                 self.deleted_objects = []
200                 if not self.get_queryset():
201                         return []
202
203                 saved_instances = []
204                 for form in self.initial_forms:
205                         pk_name = self._pk_field.name
206                         raw_pk_value = form._raw_value(pk_name)
207
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)
212
213                         obj = self._existing_object(pk_value)
214                         if form.should_delete():
215                                 self.deleted_objects.append(obj)
216                                 obj.delete()
217                                 continue
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))
221                                 if not commit:
222                                         self.saved_forms.append(form)
223                 return saved_instances
224
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():
229                                 continue
230                         # If someone has marked an add form for deletion, don't save the
231                         # object.
232                         if form.should_delete():
233                                 continue
234                         self.new_objects.append(self.save_new(form, commit=commit))
235                         if not commit:
236                                 self.saved_forms.append(form)
237                 return self.new_objects
238
239
240 class ContentletInlineFormSet(ContainerInlineFormSet):
241         def __init__(self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
242                 if instance is None:
243                         self.instance = self.fk.rel.to()
244                 else:
245                         self.instance = instance
246                 
247                 try:
248                         containers = list(self.instance.containers[0])
249                 except ObjectDoesNotExist:
250                         containers = []
251         
252                 super(ContentletInlineFormSet, self).__init__(containers, data, files, instance, save_as_new, prefix, queryset)
253         
254         def get_container_instances(self, containers, qs):
255                 qs = qs.filter(name__in=containers)
256                 container_instances = []
257                 for container in qs:
258                         container_instances.append(container)
259                         containers.remove(container.name)
260                 return container_instances, qs
261         
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])
265                 
266                 return super(ContentletInlineFormSet, self)._construct_form(i, **kwargs)
267
268
269 class ContentReferenceInlineFormSet(ContainerInlineFormSet):
270         def __init__(self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
271                 if instance is None:
272                         self.instance = self.fk.rel.to()
273                 else:
274                         self.instance = instance
275                 
276                 try:
277                         containers = list(self.instance.containers[1])
278                 except ObjectDoesNotExist:
279                         containers = []
280         
281                 super(ContentReferenceInlineFormSet, self).__init__(containers, data, files, instance, save_as_new, prefix, queryset)
282         
283         def get_container_instances(self, containers, qs):
284                 filter = Q()
285                 
286                 for name, ct in containers:
287                         filter |= Q(name=name, content_type=ct)
288                 
289                 qs = qs.filter(filter)
290                 container_instances = []
291                 for container in qs:
292                         container_instances.append(container)
293                         containers.remove((container.name, container.content_type))
294                 return container_instances, qs
295
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)
300
301                 return super(ContentReferenceInlineFormSet, self)._construct_form(i, **kwargs)