-
-
Notifications
You must be signed in to change notification settings - Fork 782
/
forms.py
249 lines (202 loc) · 8.73 KB
/
forms.py
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import os.path
from copy import deepcopy
from typing import Iterable
from django import forms
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from .resources import ModelResource
class ImportExportFormBase(forms.Form):
resource = forms.ChoiceField(
label=_("Resource"),
choices=(),
required=False,
)
format = forms.ChoiceField(
label=_("Format"),
choices=(),
)
def __init__(self, formats, resources, *args, **kwargs):
super().__init__(*args, **kwargs)
self._init_resources(resources)
self._init_formats(formats)
def _init_resources(self, resources):
if not resources:
raise ValueError("no defined resources")
if len(resources) == 1:
self.fields["resource"].value = resources[0].get_display_name()
self.fields["resource"].widget.attrs["readonly"] = True
if len(resources) > 1:
resource_choices = []
for i, resource in enumerate(resources):
resource_choices.append((i, resource.get_display_name()))
self.fields["resource"].choices = resource_choices
def _init_formats(self, formats):
if not formats:
raise ValueError("invalid formats list")
choices = [(str(i), f().get_title()) for i, f in enumerate(formats)]
if len(formats) == 1:
field = self.fields["format"]
field.value = formats[0]().get_title()
field.initial = 0
field.widget.attrs["readonly"] = True
if len(formats) > 1:
choices.insert(0, ("", "---"))
self.fields["format"].choices = choices
class ImportForm(ImportExportFormBase):
import_file = forms.FileField(label=_("File to import"))
# field ordered for usability:
# ensure that the 'file' select appears before 'format'
# so that the 'guess_format' js logic makes sense
field_order = ["resource", "import_file", "format"]
def __init__(self, formats, resources, *args, **kwargs):
super().__init__(formats, resources, *args, **kwargs)
if len(formats) > 1:
self.fields["import_file"].widget.attrs["class"] = "guess_format"
self.fields["format"].widget.attrs["class"] = "guess_format"
@property
def media(self):
extra = "" if settings.DEBUG else ".min"
return forms.Media(
js=(
f"admin/js/vendor/jquery/jquery{extra}.js",
"admin/js/jquery.init.js",
"import_export/guess_format.js",
)
)
class ConfirmImportForm(forms.Form):
import_file_name = forms.CharField(widget=forms.HiddenInput())
original_file_name = forms.CharField(widget=forms.HiddenInput())
format = forms.CharField(widget=forms.HiddenInput())
resource = forms.CharField(widget=forms.HiddenInput(), required=False)
def clean_import_file_name(self):
data = self.cleaned_data["import_file_name"]
data = os.path.basename(data)
return data
class ExportForm(ImportExportFormBase):
export_items = forms.MultipleChoiceField(
widget=forms.MultipleHiddenInput(), required=False
)
class SelectableFieldsExportForm(ExportForm):
def __init__(self, formats, resources, *args, **kwargs):
super().__init__(formats, resources, *args, **kwargs)
self._init_selectable_fields(resources)
def _init_selectable_fields(self, resources: Iterable[ModelResource]) -> None:
"""
Create `BooleanField(s)` for resource fields
"""
self.resources = resources
self.is_selectable_fields_form = True
self.resource_fields = {resource.__name__: list() for resource in resources}
for resource in resources:
self._create_boolean_fields(resource)
def _create_boolean_fields(self, resource: ModelResource) -> None:
# Initiate resource to get ordered export fields
fields = resource().get_export_order()
boolean_fields = [] # will be used for ordering the fields
for field in fields:
field_name = self.create_boolean_field_name(resource, field)
boolean_field = forms.BooleanField(
label=field.replace("_", " ").title(),
initial=True,
required=False,
)
# These attributes will be used for rendering in template
boolean_field.is_selectable_field = True
boolean_field.resource_name = resource.__name__
self.fields[field_name] = boolean_field
boolean_fields.append(field_name)
self.order_fields(boolean_fields) # Order fields by boolean fields
self.resource_fields[resource.__name__] = boolean_fields
@staticmethod
def create_boolean_field_name(resource: ModelResource, field_name: str) -> str:
"""
Create field name by combining `resource_name` + `field_name` to prevent
confliction between resource fields with same name
Example:
BookResource + name -> bookresource_name
BookResourceWithNames + name -> bookresourcewithnames_name
"""
return resource.__name__.lower() + "_" + field_name
def full_clean(self) -> None:
return super().full_clean()
def clean(self):
selected_resource = self.get_selected_resource()
if selected_resource:
# Remove fields for not selected resources
self._remove_unselected_resource_fields(selected_resource)
# Normalize resource field names
self._normalize_resource_fields(selected_resource)
# Validate at least one field is selected for selected resource
self._validate_any_field_selected(selected_resource)
return self.cleaned_data
def _remove_unselected_resource_fields(
self, selected_resource: ModelResource
) -> None:
"""
Remove boolean fields except the fields for selected resource
"""
_cleaned_data = deepcopy(self.cleaned_data)
for resource_name, fields in self.resource_fields.items():
if selected_resource.__name__ == resource_name:
# Skip selected resource
continue
for field in fields:
del _cleaned_data[field]
self.cleaned_data = _cleaned_data
def get_selected_resource(self):
"""
Get selected resource
"""
if not getattr(self, "cleaned_data", None):
raise forms.ValidationError(
_("Form is not validated, call `is_valid` first")
)
# Return selected resource by index
resource_index = 0
if "resource" in self.cleaned_data:
try:
resource_index = int(self.cleaned_data["resource"])
except ValueError:
pass
return self.resources[resource_index]
def _normalize_resource_fields(self, selected_resource: ModelResource) -> dict:
"""
Field names are combination of resource_name + field_name,
normalize field names by removing resource name
"""
selected_resource_name = selected_resource.__name__.lower() + "_"
_cleaned_data = {}
self._selected_resource_fields = []
for k, v in self.cleaned_data.items():
if selected_resource_name in k:
field_name = k.replace(selected_resource_name, "")
_cleaned_data[field_name] = v
if v is True:
# Add to _selected_resource_fields to determine what
# fields were selected for export
self._selected_resource_fields.append(field_name)
continue
_cleaned_data[k] = v
self.cleaned_data = _cleaned_data
def get_selected_resource_export_fields(self):
selected_resource = self.get_selected_resource()
# Initialize resource to use `get_export_order` method
resource_fields = selected_resource().get_export_order()
return [
field
for field, value in self.cleaned_data.items()
if field in resource_fields and value is True
]
def _validate_any_field_selected(self, resource) -> None:
"""
Validate if any field for resource was selected in form data
"""
resource_fields = [field for field in resource().get_export_order()]
if not any([v for k, v in self.cleaned_data.items() if k in resource_fields]):
raise forms.ValidationError(
_("""Select at least 1 field for "%(resource_name)s" to export"""),
code="invalid",
params={
"resource_name": resource.get_display_name(),
},
)