Initial commit of Gilbert, an advanced Django administration interface.
[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.forms.models import model_to_dict, fields_for_model, ModelFormMetaclass, ModelForm, BaseInlineFormSet
5 from django.forms.formsets import TOTAL_FORM_COUNT
6 from django.template import loader, loader_tags, TemplateDoesNotExist, Context, Template as DjangoTemplate
7 from django.utils.datastructures import SortedDict
8 from philo.admin.widgets import ModelLookupWidget
9 from philo.models import Entity, Template, Contentlet, ContentReference
10 from philo.models.fields import RelationshipField
11 from philo.utils import fattr
12
13
14 __all__ = ('EntityForm', )
15
16
17 def proxy_fields_for_entity_model(entity_model, fields=None, exclude=None, widgets=None, formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)):
18         field_list = []
19         ignored = []
20         opts = entity_model._entity_meta
21         for f in opts.proxy_fields:
22                 if fields and not f.name in fields:
23                         continue
24                 if exclude and f.name in exclude:
25                         continue
26                 if widgets and f.name in widgets:
27                         kwargs = {'widget': widgets[f.name]}
28                 else:
29                         kwargs = {}
30                 formfield = formfield_callback(f, **kwargs)
31                 if formfield:
32                         field_list.append((f.name, formfield))
33                 else:
34                         ignored.append(f.name)
35         field_dict = SortedDict(field_list)
36         if fields:
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)]
40                 )
41         return field_dict
42
43
44 # BEGIN HACK - This will not be required after http://code.djangoproject.com/ticket/14082 has been resolved
45
46 class EntityFormBase(ModelForm):
47         pass
48
49 _old_metaclass_new = ModelFormMetaclass.__new__
50
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
55         return new_class
56
57 ModelFormMetaclass.__new__ = staticmethod(_new_metaclass_new)
58
59 # END HACK
60
61
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:
67                         new_initial = {}
68                         for f in instance._entity_meta.proxy_fields:
69                                 if self._meta.fields and not f.name in self._meta.fields:
70                                         continue
71                                 if self._meta.exclude and f.name in self._meta.exclude:
72                                         continue
73                                 new_initial[f.name] = f.value_from_object(instance)
74                 else:
75                         new_initial = {}
76                 if initial is not None:
77                         new_initial.update(initial)
78                 kwargs['initial'] = new_initial
79                 super(EntityForm, self).__init__(*args, **kwargs)
80         
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)
85                 
86                 for f in instance._entity_meta.proxy_fields:
87                         if self._meta.fields and f.name not in self._meta.fields:
88                                 continue
89                         setattr(instance, f.attname, cleaned_data[f.name])
90                 
91                 if commit:
92                         instance.save()
93                         self.save_m2m()
94                 
95                 return instance
96
97
98 def validate_template(template):
99         """
100         Makes sure that the template and all included or extended templates are valid.
101         """ 
102         for node in template.nodelist:
103                 try:
104                         if isinstance(node, loader_tags.ExtendsNode):
105                                 extended_template = node.get_parent(Context())
106                                 validate_template(extended_template)
107                         elif isinstance(node, loader_tags.IncludeNode):
108                                 included_template = loader.get_template(node.template_name.resolve(Context()))
109                                 validate_template(extended_template)
110                 except Exception, e:
111                         raise ValidationError("Template code invalid. Error was: %s: %s" % (e.__class__.__name__, e))
112
113
114 class TemplateForm(ModelForm):
115         def clean_code(self):
116                 code = self.cleaned_data['code']
117                 try:
118                         t = DjangoTemplate(code)
119                 except Exception, e:
120                         raise ValidationError("Template code invalid. Error was: %s: %s" % (e.__class__.__name__, e))
121
122                 validate_template(t)
123                 return code
124
125         class Meta:
126                 model = Template
127
128
129 class ContainerForm(ModelForm):
130         def __init__(self, *args, **kwargs):
131                 super(ContainerForm, self).__init__(*args, **kwargs)
132                 self.verbose_name = self.instance.name.replace('_', ' ')
133
134
135 class ContentletForm(ContainerForm):
136         content = forms.CharField(required=False, widget=AdminTextareaWidget)
137         
138         def should_delete(self):
139                 return not bool(self.cleaned_data['content'])
140         
141         class Meta:
142                 model = Contentlet
143                 fields = ['name', 'content', 'dynamic']
144
145
146 class ContentReferenceForm(ContainerForm):
147         def __init__(self, *args, **kwargs):
148                 super(ContentReferenceForm, self).__init__(*args, **kwargs)
149                 try:
150                         self.fields['content_id'].widget = ModelLookupWidget(self.instance.content_type)
151                 except ObjectDoesNotExist:
152                         # This will happen when an empty form (which we will never use) gets instantiated.
153                         pass
154         
155         def should_delete(self):
156                 return (self.cleaned_data['content_id'] is None)
157         
158         class Meta:
159                 model = ContentReference
160                 fields = ['name', 'content_id']
161
162
163 class ContainerInlineFormSet(BaseInlineFormSet):
164         def __init__(self, containers, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
165                 # Unfortunately, I need to add some things to BaseInline between its __init__ and its super call, so
166                 # a lot of this is repetition.
167                 
168                 # Start cribbed from BaseInline
169                 from django.db.models.fields.related import RelatedObject
170                 self.save_as_new = save_as_new
171                 # is there a better way to get the object descriptor?
172                 self.rel_name = RelatedObject(self.fk.rel.to, self.model, self.fk).get_accessor_name()
173                 if self.fk.rel.field_name == self.fk.rel.to._meta.pk.name:
174                         backlink_value = self.instance
175                 else:
176                         backlink_value = getattr(self.instance, self.fk.rel.field_name)
177                 if queryset is None:
178                         queryset = self.model._default_manager
179                 qs = queryset.filter(**{self.fk.name: backlink_value})
180                 # End cribbed from BaseInline
181                 
182                 self.container_instances, qs = self.get_container_instances(containers, qs)
183                 self.extra_containers = containers
184                 self.extra = len(self.extra_containers)
185                 super(BaseInlineFormSet, self).__init__(data, files, prefix=prefix, queryset=qs)
186         
187         def get_container_instances(self, containers, qs):
188                 raise NotImplementedError
189         
190         def total_form_count(self):
191                 if self.data or self.files:
192                         return self.management_form.cleaned_data[TOTAL_FORM_COUNT]
193                 else:
194                         return self.initial_form_count() + self.extra
195         
196         def save_existing_objects(self, commit=True):
197                 self.changed_objects = []
198                 self.deleted_objects = []
199                 if not self.get_queryset():
200                         return []
201
202                 saved_instances = []
203                 for form in self.initial_forms:
204                         pk_name = self._pk_field.name
205                         raw_pk_value = form._raw_value(pk_name)
206
207                         # clean() for different types of PK fields can sometimes return
208                         # the model instance, and sometimes the PK. Handle either.
209                         pk_value = form.fields[pk_name].clean(raw_pk_value)
210                         pk_value = getattr(pk_value, 'pk', pk_value)
211
212                         obj = self._existing_object(pk_value)
213                         if form.should_delete():
214                                 self.deleted_objects.append(obj)
215                                 obj.delete()
216                                 continue
217                         if form.has_changed():
218                                 self.changed_objects.append((obj, form.changed_data))
219                                 saved_instances.append(self.save_existing(form, obj, commit=commit))
220                                 if not commit:
221                                         self.saved_forms.append(form)
222                 return saved_instances
223
224         def save_new_objects(self, commit=True):
225                 self.new_objects = []
226                 for form in self.extra_forms:
227                         if not form.has_changed():
228                                 continue
229                         # If someone has marked an add form for deletion, don't save the
230                         # object.
231                         if form.should_delete():
232                                 continue
233                         self.new_objects.append(self.save_new(form, commit=commit))
234                         if not commit:
235                                 self.saved_forms.append(form)
236                 return self.new_objects
237
238
239 class ContentletInlineFormSet(ContainerInlineFormSet):
240         def __init__(self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
241                 if instance is None:
242                         self.instance = self.fk.rel.to()
243                 else:
244                         self.instance = instance
245                 
246                 try:
247                         containers = list(self.instance.containers[0])
248                 except ObjectDoesNotExist:
249                         containers = []
250         
251                 super(ContentletInlineFormSet, self).__init__(containers, data, files, instance, save_as_new, prefix, queryset)
252         
253         def get_container_instances(self, containers, qs):
254                 qs = qs.filter(name__in=containers)
255                 container_instances = []
256                 for container in qs:
257                         container_instances.append(container)
258                         containers.remove(container.name)
259                 return container_instances, qs
260         
261         def _construct_form(self, i, **kwargs):
262                 if i >= self.initial_form_count(): # and not kwargs.get('instance'):
263                         kwargs['instance'] = self.model(name=self.extra_containers[i - self.initial_form_count() - 1])
264                 
265                 return super(ContentletInlineFormSet, self)._construct_form(i, **kwargs)
266
267
268 class ContentReferenceInlineFormSet(ContainerInlineFormSet):
269         def __init__(self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None):
270                 if instance is None:
271                         self.instance = self.fk.rel.to()
272                 else:
273                         self.instance = instance
274                 
275                 try:
276                         containers = list(self.instance.containers[1])
277                 except ObjectDoesNotExist:
278                         containers = []
279         
280                 super(ContentReferenceInlineFormSet, self).__init__(containers, data, files, instance, save_as_new, prefix, queryset)
281         
282         def get_container_instances(self, containers, qs):
283                 qs = qs.filter(name__in=[c[0] for c in containers])
284                 container_instances = []
285                 for container in qs:
286                         container_instances.append(container)
287                         containers.remove((container.name, container.content_type))
288                 return container_instances, qs
289
290         def _construct_form(self, i, **kwargs):
291                 if i >= self.initial_form_count(): # and not kwargs.get('instance'):
292                         name, content_type = self.extra_containers[i - self.initial_form_count() - 1]
293                         kwargs['instance'] = self.model(name=name, content_type=content_type)
294
295                 return super(ContentReferenceInlineFormSet, self)._construct_form(i, **kwargs)