1 from django.forms.models import ModelFormMetaclass, ModelForm
2 from django.utils.datastructures import SortedDict
3 from philo.utils import fattr
6 __all__ = ('EntityForm',)
9 def proxy_fields_for_entity_model(entity_model, fields=None, exclude=None, widgets=None, formfield_callback=lambda f, **kwargs: f.formfield(**kwargs)):
12 opts = entity_model._entity_meta
13 for f in opts.proxy_fields:
16 if fields and not f.name in fields:
18 if exclude and f.name in exclude:
20 if widgets and f.name in widgets:
21 kwargs = {'widget': widgets[f.name]}
24 formfield = formfield_callback(f, **kwargs)
26 field_list.append((f.name, formfield))
28 ignored.append(f.name)
29 field_dict = SortedDict(field_list)
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)]
38 # BEGIN HACK - This will not be required after http://code.djangoproject.com/ticket/14082 has been resolved
40 class EntityFormBase(ModelForm):
43 _old_metaclass_new = ModelFormMetaclass.__new__
45 def _new_metaclass_new(cls, name, bases, attrs):
46 formfield_callback = attrs.get('formfield_callback', None)
47 if formfield_callback is None:
48 formfield_callback = lambda f, **kwargs: f.formfield(**kwargs)
49 new_class = _old_metaclass_new(cls, name, bases, attrs)
50 opts = new_class._meta
51 if issubclass(new_class, EntityFormBase) and opts.model:
52 # "override" proxy fields with declared fields by excluding them if there's a name conflict.
53 exclude = (list(opts.exclude or []) + new_class.declared_fields.keys()) or None
54 proxy_fields = proxy_fields_for_entity_model(opts.model, opts.fields, exclude, opts.widgets, formfield_callback) # don't pass in formfield_callback
55 new_class.proxy_fields = proxy_fields
56 new_class.base_fields.update(proxy_fields)
59 ModelFormMetaclass.__new__ = staticmethod(_new_metaclass_new)
64 class EntityForm(EntityFormBase): # Would inherit from ModelForm directly if it weren't for the above HACK
65 def __init__(self, *args, **kwargs):
66 initial = kwargs.pop('initial', None)
67 instance = kwargs.get('instance', None)
68 if instance is not None:
70 for f in instance._entity_meta.proxy_fields:
71 if self._meta.fields and not f.name in self._meta.fields:
73 if self._meta.exclude and f.name in self._meta.exclude:
75 new_initial[f.name] = f.value_from_object(instance)
78 if initial is not None:
79 new_initial.update(initial)
80 kwargs['initial'] = new_initial
81 super(EntityForm, self).__init__(*args, **kwargs)
83 @fattr(alters_data=True)
84 def save(self, commit=True):
85 cleaned_data = self.cleaned_data
86 instance = super(EntityForm, self).save(commit=False)
88 for f in instance._entity_meta.proxy_fields:
89 if not f.editable or not f.name in cleaned_data:
91 if self._meta.fields and f.name not in self._meta.fields:
93 if self._meta.exclude and f.name in self._meta.exclude:
95 setattr(instance, f.attname, f.get_storage_value(cleaned_data[f.name]))