Merge branch 'entity_raw_id_fields'
[philo.git] / contrib / cowell / forms.py
1 from django.forms.models import ModelFormMetaclass, ModelForm
2 from django.utils.datastructures import SortedDict
3 from philo.utils import fattr
4
5
6 __all__ = ('EntityForm',)
7
8
9 def proxy_fields_for_entity_model(entity_model, fields=None, exclude=None, widgets=None, formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)):
10         field_list = []
11         ignored = []
12         opts = entity_model._entity_meta
13         for f in opts.proxy_fields:
14                 if not f.editable:
15                         continue
16                 if fields and not f.name in fields:
17                         continue
18                 if exclude and f.name in exclude:
19                         continue
20                 if widgets and f.name in widgets:
21                         kwargs = {'widget': widgets[f.name]}
22                 else:
23                         kwargs = {}
24                 formfield = formfield_callback(f, **kwargs)
25                 if formfield:
26                         field_list.append((f.name, formfield))
27                 else:
28                         ignored.append(f.name)
29         field_dict = SortedDict(field_list)
30         if fields:
31                 field_dict = SortedDict(
32                         [(f, field_dict.get(f)) for f in fields
33                                 if ((not exclude) or (exclude and f not in exclude)) and (f not in ignored) and (f in field_dict)]
34                 )
35         return field_dict
36
37
38 # BEGIN HACK - This will not be required after http://code.djangoproject.com/ticket/14082 has been resolved
39
40 class EntityFormBase(ModelForm):
41         pass
42
43 _old_metaclass_new = ModelFormMetaclass.__new__
44
45 def _new_metaclass_new(cls, name, bases, attrs):
46         new_class = _old_metaclass_new(cls, name, bases, attrs)
47         if issubclass(new_class, EntityFormBase) and new_class._meta.model:
48                 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
49         return new_class
50
51 ModelFormMetaclass.__new__ = staticmethod(_new_metaclass_new)
52
53 # END HACK
54
55
56 class EntityForm(EntityFormBase): # Would inherit from ModelForm directly if it weren't for the above HACK
57         def __init__(self, *args, **kwargs):
58                 initial = kwargs.pop('initial', None)
59                 instance = kwargs.get('instance', None)
60                 if instance is not None:
61                         new_initial = {}
62                         for f in instance._entity_meta.proxy_fields:
63                                 if self._meta.fields and not f.name in self._meta.fields:
64                                         continue
65                                 if self._meta.exclude and f.name in self._meta.exclude:
66                                         continue
67                                 new_initial[f.name] = f.value_from_object(instance)
68                 else:
69                         new_initial = {}
70                 if initial is not None:
71                         new_initial.update(initial)
72                 kwargs['initial'] = new_initial
73                 super(EntityForm, self).__init__(*args, **kwargs)
74         
75         @fattr(alters_data=True)
76         def save(self, commit=True):
77                 cleaned_data = self.cleaned_data
78                 instance = super(EntityForm, self).save(commit=False)
79                 
80                 for f in instance._entity_meta.proxy_fields:
81                         if not f.editable or not f.name in cleaned_data:
82                                 continue
83                         if self._meta.fields and f.name not in self._meta.fields:
84                                 continue
85                         if self._meta.exclude and f.name in self._meta.exclude:
86                                 continue
87                         setattr(instance, f.attname, cleaned_data[f.name])
88                 
89                 if commit:
90                         instance.save()
91                         self.save_m2m()
92                 
93                 return instance
94
95         
96         def apply_data(self, cleaned_data):
97                 self.value = cleaned_data.get('value', None)
98         
99         def apply_data(self, cleaned_data):
100                 if 'value' in cleaned_data and cleaned_data['value'] is not None:
101                         self.value = cleaned_data['value']
102                 else:
103                         self.content_type = cleaned_data.get('content_type', None)
104                         # If there is no value set in the cleaned data, clear the stored value.
105                         self.object_id = None
106         
107         def apply_data(self, cleaned_data):
108                 if 'value' in cleaned_data and cleaned_data['value'] is not None:
109                         self.value = cleaned_data['value']
110                 else:
111                         self.content_type = cleaned_data.get('content_type', None)
112                         # If there is no value set in the cleaned data, clear the stored value.
113                         self.value = []