-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathforms.py
More file actions
153 lines (130 loc) · 5.71 KB
/
forms.py
File metadata and controls
153 lines (130 loc) · 5.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4 coding=utf-8
#
# This software is derived from EAV-Django originally written and
# copyrighted by Andrey Mikhaylenko <http://pypi.python.org/pypi/eav-django>
#
# This is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with EAV-Django. If not, see <http://gnu.org/licenses/>.
'''
#####
forms
#####
The forms used for admin integration
Classes
-------
'''
from copy import deepcopy
from django.conf import settings
from django.forms import BooleanField, CharField, DateField, DateTimeField, FloatField, \
IntegerField, ModelForm, ChoiceField, ValidationError
from django.contrib.admin.widgets import AdminSplitDateTime
from django.utils.translation import ugettext_lazy as _
class BaseDynamicEntityForm(ModelForm):
'''
ModelForm for entity with support for EAV attributes. Form fields are
created on the fly depending on Schema defined for given entity instance.
If no schema is defined (i.e. the entity instance has not been saved yet),
only static fields are used. However, on form validation the schema will be
retrieved and EAV fields dynamically added to the form, so when the
validation is actually done, all EAV fields are present in it (unless
Rubric is not defined).
'''
FIELD_CLASSES = {
'text': CharField,
'float': FloatField,
'int': IntegerField,
'date': DateField,
'datetime': DateTimeField,
'bool': BooleanField,
'enum': ChoiceField,
}
def __init__(self, data=None, *args, **kwargs):
super(BaseDynamicEntityForm, self).__init__(data, *args, **kwargs)
config_cls = self.instance._eav_config_cls
self.entity = getattr(self.instance, config_cls.eav_attr)
self._build_dynamic_fields()
use_l10n = getattr(settings, 'USE_L10N')
if use_l10n == True:
self.localize_fields()
def localize_fields(self):
"""
set localization to True for all fields
"""
for name, field in self.fields.items():
widget_type = field.widget.__class__.__name__
if widget_type != "DateInput" and widget_type != "DateTimeInput" and widget_type != "TimeInput": #do not localize date / time input widgets
field.localize = True
field.widget.is_localized = True
else:
field.localize = False
field.widget.is_localized = False
if widget_type == "DateInput":
field.widget.format=settings.DATE_FORMAT
if widget_type == "DateTimeInput":
field.widget.format=settings.DATETIME_FORMAT
if widget_type == "TimeInput":
field.widget.format=settings.TIME_FORMAT
def _build_dynamic_fields(self):
# reset form fields
self.fields = deepcopy(self.base_fields)
for attribute in self.entity.get_all_attributes():
value = getattr(self.entity, attribute.slug)
defaults = {
'label': attribute.name.capitalize(),
'required': attribute.required,
'help_text': attribute.help_text,
'validators': attribute.get_validators(),
}
datatype = attribute.datatype
if datatype == attribute.TYPE_ENUM:
enums = attribute.get_choices() \
.values_list('id', 'value')
choices = [('', '-----')] + list(enums)
defaults.update({'choices': choices})
if value:
defaults.update({'initial': value.pk})
elif datatype == attribute.TYPE_DATE_TIME:
defaults.update({'widget': AdminSplitDateTime})
elif datatype == attribute.TYPE_OBJECT:
continue
MappedField = self.FIELD_CLASSES[datatype]
self.fields[attribute.slug] = MappedField(**defaults)
# fill initial data (if attribute was already defined)
if value and not datatype == attribute.TYPE_ENUM: #enum done above
self.initial[attribute.slug] = value
def save(self, commit=True):
"""
Saves this ``form``'s cleaned_data into model instance
``self.instance`` and related EAV attributes.
Returns ``instance``.
"""
if self.errors:
raise ValueError(_(u"The %s could not be saved because the data"
u"didn't validate.") % \
self.instance._meta.object_name)
# create entity instance, don't save yet
instance = super(BaseDynamicEntityForm, self).save(commit=False)
# assign attributes
for attribute in self.entity.get_all_attributes():
value = self.cleaned_data.get(attribute.slug)
if attribute.datatype == attribute.TYPE_ENUM:
if value:
value = attribute.enum_group.enums.get(pk=value)
else:
value = None
setattr(self.entity, attribute.slug, value)
# save entity and its attributes
if commit:
instance.save()
return instance