feincms3-api 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- feincms3_api/__init__.py +1 -0
- feincms3_api/adapters.py +303 -0
- feincms3_api/admin.py +93 -0
- feincms3_api/api.py +66 -0
- feincms3_api/apps.py +70 -0
- feincms3_api/auth.py +29 -0
- feincms3_api/cabinet.py +78 -0
- feincms3_api/codecs.py +495 -0
- feincms3_api/conf.py +31 -0
- feincms3_api/content.py +312 -0
- feincms3_api/errors.py +53 -0
- feincms3_api/forms.py +36 -0
- feincms3_api/formsets.py +135 -0
- feincms3_api/http.py +195 -0
- feincms3_api/incubator/__init__.py +6 -0
- feincms3_api/incubator/autotranslate/__init__.py +0 -0
- feincms3_api/incubator/autotranslate/apps.py +47 -0
- feincms3_api/incubator/autotranslate/backends/__init__.py +78 -0
- feincms3_api/incubator/autotranslate/backends/anthropic.py +98 -0
- feincms3_api/incubator/autotranslate/conf.py +59 -0
- feincms3_api/incubator/autotranslate/datasets.py +428 -0
- feincms3_api/incubator/autotranslate/fields.py +213 -0
- feincms3_api/incubator/autotranslate/links.py +122 -0
- feincms3_api/incubator/autotranslate/loader.py +1250 -0
- feincms3_api/incubator/autotranslate/management/__init__.py +0 -0
- feincms3_api/incubator/autotranslate/management/commands/__init__.py +0 -0
- feincms3_api/incubator/autotranslate/management/commands/f3autotranslate.py +162 -0
- feincms3_api/incubator/autotranslate/management/commands/f3autotranslateload.py +92 -0
- feincms3_api/incubator/autotranslate/review.py +104 -0
- feincms3_api/incubator/autotranslate/strings.py +313 -0
- feincms3_api/incubator/autotranslate/translate.py +260 -0
- feincms3_api/kinds.py +86 -0
- feincms3_api/management/__init__.py +0 -0
- feincms3_api/management/commands/__init__.py +0 -0
- feincms3_api/management/commands/f3api_cleanup.py +18 -0
- feincms3_api/management/commands/f3api_schema.py +32 -0
- feincms3_api/management/commands/f3api_token.py +39 -0
- feincms3_api/migrations/0001_initial.py +91 -0
- feincms3_api/migrations/0002_upload.py +61 -0
- feincms3_api/migrations/__init__.py +0 -0
- feincms3_api/models.py +189 -0
- feincms3_api/paths.py +43 -0
- feincms3_api/reading.py +120 -0
- feincms3_api/references.py +123 -0
- feincms3_api/resources.py +580 -0
- feincms3_api/schema.py +80 -0
- feincms3_api/snapshot.py +110 -0
- feincms3_api/templates/admin/feincms3_api/apitoken/created.html +19 -0
- feincms3_api/writing.py +255 -0
- feincms3_api-0.0.1.dist-info/METADATA +69 -0
- feincms3_api-0.0.1.dist-info/RECORD +53 -0
- feincms3_api-0.0.1.dist-info/WHEEL +4 -0
- feincms3_api-0.0.1.dist-info/licenses/LICENSE +29 -0
feincms3_api/content.py
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Planning a write: every check first, then the saves
|
|
3
|
+
|
|
4
|
+
A write is planned completely before anything is saved: the regions, the
|
|
5
|
+
plugin types allowed in them, the depths, the permissions, and what happens
|
|
6
|
+
to every row of every inline (plugins and other inlines): it stays, changes,
|
|
7
|
+
is added or deleted. Problems are collected with their paths, so a write
|
|
8
|
+
fails as a whole with all of them listed, or succeeds as a whole.
|
|
9
|
+
|
|
10
|
+
The rows are then bound to the admin's formsets (``formsets.py``).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
|
|
15
|
+
from content_editor.admin import ContentEditorInline
|
|
16
|
+
from django.contrib.admin.models import LogEntry
|
|
17
|
+
from django.utils.translation import gettext as _
|
|
18
|
+
|
|
19
|
+
from feincms3_api.codecs import label
|
|
20
|
+
from feincms3_api.formsets import Row, bind_formset, formset_errors, prefixes
|
|
21
|
+
from feincms3_api.resources import allowed_types, fk_name
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def check_depths(items, containers, path):
|
|
25
|
+
"""
|
|
26
|
+
The depths of a flat region, checked: the first plugin is at depth 0,
|
|
27
|
+
and a plugin is at most one deeper than the innermost container still
|
|
28
|
+
open before it
|
|
29
|
+
"""
|
|
30
|
+
errors = []
|
|
31
|
+
open_containers = []
|
|
32
|
+
for index, item in enumerate(items):
|
|
33
|
+
depth = item.get("depth", 0) if isinstance(item, dict) else 0
|
|
34
|
+
if not isinstance(depth, int) or isinstance(depth, bool) or depth < 0:
|
|
35
|
+
errors.append(
|
|
36
|
+
{"path": f"{path}[{index}].depth", "message": "Expected 0 or more."}
|
|
37
|
+
)
|
|
38
|
+
continue
|
|
39
|
+
deepest = open_containers[-1] + 1 if open_containers else 0
|
|
40
|
+
if depth > deepest:
|
|
41
|
+
errors.append(
|
|
42
|
+
{
|
|
43
|
+
"path": f"{path}[{index}].depth",
|
|
44
|
+
"message": f"Can be at most {deepest}: a plugin can only be"
|
|
45
|
+
" one deeper than a container plugin before it.",
|
|
46
|
+
}
|
|
47
|
+
)
|
|
48
|
+
continue
|
|
49
|
+
while open_containers and open_containers[-1] >= depth:
|
|
50
|
+
open_containers.pop()
|
|
51
|
+
if isinstance(item, dict) and item.get("type") in containers:
|
|
52
|
+
open_containers.append(depth)
|
|
53
|
+
return errors
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class Planner:
|
|
57
|
+
"""
|
|
58
|
+
What a write does to the rows of an object's inlines
|
|
59
|
+
|
|
60
|
+
``obj`` may be new; for an existing object, every row it has starts
|
|
61
|
+
out unchanged. ``content()``, ``inlines()`` and ``plugin()`` change
|
|
62
|
+
them, ``bind()`` binds them to the admin's formsets.
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
def __init__(self, api, resource, request, obj):
|
|
66
|
+
self.api, self.resource, self.request, self.obj = api, resource, request, obj
|
|
67
|
+
self.existing_obj = obj if obj.pk is not None else None
|
|
68
|
+
self.errors = []
|
|
69
|
+
self.inlines = resource.model_admin.get_inline_instances(
|
|
70
|
+
request, self.existing_obj
|
|
71
|
+
)
|
|
72
|
+
plugin_inlines = [i for i in self.inlines if _is_plugin_inline(i)]
|
|
73
|
+
self.by_type = {label(inline.model): inline for inline in self.inlines}
|
|
74
|
+
self.containers = {
|
|
75
|
+
label(i.model)
|
|
76
|
+
for i in plugin_inlines
|
|
77
|
+
if getattr(i.model, "container", False)
|
|
78
|
+
}
|
|
79
|
+
self.region_keys = [region.key for region in resource.regions(obj)]
|
|
80
|
+
self.allowed = allowed_types(plugin_inlines, self.region_keys)
|
|
81
|
+
|
|
82
|
+
self.rows = {inline: [] for inline in self.inlines}
|
|
83
|
+
self.existing = {}
|
|
84
|
+
visible, _hidden = resource.plugins(request, plugin_inlines, obj)
|
|
85
|
+
positions = {}
|
|
86
|
+
for plugin, inline in visible:
|
|
87
|
+
index = positions.get(plugin.region, 0)
|
|
88
|
+
positions[plugin.region] = index + 1
|
|
89
|
+
self._add_existing(inline, plugin, f"content.{plugin.region}[{index}]")
|
|
90
|
+
for inline in self.inlines:
|
|
91
|
+
if not _is_plugin_inline(inline):
|
|
92
|
+
type_label = label(inline.model)
|
|
93
|
+
for index, item in enumerate(
|
|
94
|
+
resource.inline_objects(request, inline, self.existing_obj)
|
|
95
|
+
):
|
|
96
|
+
self._add_existing(inline, item, f"inlines.{type_label}[{index}]")
|
|
97
|
+
self.used = set()
|
|
98
|
+
self._fields = {}
|
|
99
|
+
|
|
100
|
+
def _add_existing(self, inline, instance, path):
|
|
101
|
+
row = Row(instance=instance, path=path)
|
|
102
|
+
self.rows[inline].append(row)
|
|
103
|
+
self.existing[label(type(instance)), instance.pk] = row
|
|
104
|
+
|
|
105
|
+
def error(self, path, message):
|
|
106
|
+
self.errors.append({"path": path, "message": message})
|
|
107
|
+
|
|
108
|
+
# Content ################################################################
|
|
109
|
+
|
|
110
|
+
def content(self, content, path="content"):
|
|
111
|
+
"""
|
|
112
|
+
Replace the regions in ``content``. Regions which aren't given are
|
|
113
|
+
left alone; plugins without an inline for the user (no permission)
|
|
114
|
+
are never touched.
|
|
115
|
+
"""
|
|
116
|
+
if not isinstance(content, dict):
|
|
117
|
+
self.error(path, "Expected an object.")
|
|
118
|
+
return
|
|
119
|
+
for key, items in content.items():
|
|
120
|
+
self._region(key, items, f"{path}.{key}")
|
|
121
|
+
for (type_label, plugin_id), row in self.existing.items():
|
|
122
|
+
inline = self.by_type[type_label]
|
|
123
|
+
if (
|
|
124
|
+
_is_plugin_inline(inline)
|
|
125
|
+
and row.instance.region in content
|
|
126
|
+
and (type_label, plugin_id) not in self.used
|
|
127
|
+
):
|
|
128
|
+
self._delete(inline, row, f"{path}.{row.instance.region}")
|
|
129
|
+
|
|
130
|
+
def _region(self, key, items, path):
|
|
131
|
+
if key not in self.region_keys:
|
|
132
|
+
regions = ", ".join(self.region_keys) or "none"
|
|
133
|
+
self.error(path, f"Not a region of this object; its regions are {regions}.")
|
|
134
|
+
return
|
|
135
|
+
if not isinstance(items, list):
|
|
136
|
+
self.error(path, "Expected a list.")
|
|
137
|
+
return
|
|
138
|
+
self.errors.extend(check_depths(items, self.containers, path))
|
|
139
|
+
for index, item in enumerate(items):
|
|
140
|
+
item_path = f"{path}[{index}]"
|
|
141
|
+
if not isinstance(item, dict):
|
|
142
|
+
self.error(item_path, "Expected an object.")
|
|
143
|
+
continue
|
|
144
|
+
type_label = item.get("type")
|
|
145
|
+
inline = self.by_type.get(type_label)
|
|
146
|
+
if inline is None or not _is_plugin_inline(inline):
|
|
147
|
+
self.error(
|
|
148
|
+
f"{item_path}.type",
|
|
149
|
+
f"{type_label!r} isn't a plugin type of this object, or not"
|
|
150
|
+
" one you may use.",
|
|
151
|
+
)
|
|
152
|
+
continue
|
|
153
|
+
if type_label not in self.allowed[key]:
|
|
154
|
+
self.error(
|
|
155
|
+
f"{item_path}.type", f"{type_label} isn't allowed in region {key}."
|
|
156
|
+
)
|
|
157
|
+
continue
|
|
158
|
+
extra = {
|
|
159
|
+
"region": key,
|
|
160
|
+
"ordering": (index + 1) * 10,
|
|
161
|
+
"depth": item.get("depth", 0),
|
|
162
|
+
}
|
|
163
|
+
base_fields = self._base_fields(inline)
|
|
164
|
+
extra = {
|
|
165
|
+
name: value for name, value in extra.items() if name in base_fields
|
|
166
|
+
}
|
|
167
|
+
self._item(inline, item, item_path, extra)
|
|
168
|
+
|
|
169
|
+
def _base_fields(self, inline):
|
|
170
|
+
if inline not in self._fields:
|
|
171
|
+
formset_class = inline.get_formset(self.request, self.existing_obj)
|
|
172
|
+
self._fields[inline] = formset_class.form.base_fields
|
|
173
|
+
return self._fields[inline]
|
|
174
|
+
|
|
175
|
+
# Other inlines ##########################################################
|
|
176
|
+
|
|
177
|
+
def other_inlines(self, inlines, path="inlines"):
|
|
178
|
+
"""Replace the objects of the inline types in ``inlines``"""
|
|
179
|
+
if not isinstance(inlines, dict):
|
|
180
|
+
self.error(path, "Expected an object.")
|
|
181
|
+
return
|
|
182
|
+
for type_label, items in inlines.items():
|
|
183
|
+
type_path = f"{path}.{type_label}"
|
|
184
|
+
inline = self.by_type.get(type_label)
|
|
185
|
+
if inline is None or _is_plugin_inline(inline):
|
|
186
|
+
self.error(
|
|
187
|
+
type_path,
|
|
188
|
+
f"{type_label!r} isn't an inline of this object, or not one"
|
|
189
|
+
" you may use.",
|
|
190
|
+
)
|
|
191
|
+
continue
|
|
192
|
+
if not isinstance(items, list):
|
|
193
|
+
self.error(type_path, "Expected a list.")
|
|
194
|
+
continue
|
|
195
|
+
for index, item in enumerate(items):
|
|
196
|
+
item_path = f"{type_path}[{index}]"
|
|
197
|
+
if not isinstance(item, dict):
|
|
198
|
+
self.error(item_path, "Expected an object.")
|
|
199
|
+
continue
|
|
200
|
+
if unknown := set(item) - {"id", "fields"}:
|
|
201
|
+
for key in sorted(unknown):
|
|
202
|
+
self.error(f"{item_path}.{key}", "Unknown key.")
|
|
203
|
+
continue
|
|
204
|
+
self._item(inline, {"type": type_label, **item}, item_path, {})
|
|
205
|
+
for row in self.rows[inline]:
|
|
206
|
+
if not row.new and (type_label, row.instance.pk) not in self.used:
|
|
207
|
+
self._delete(inline, row, type_path)
|
|
208
|
+
|
|
209
|
+
# One plugin #############################################################
|
|
210
|
+
|
|
211
|
+
def plugin(self, inline, plugin, wire):
|
|
212
|
+
"""Change one plugin's ``fields``"""
|
|
213
|
+
row = self.existing[label(type(plugin)), plugin.pk]
|
|
214
|
+
row.wire, row.path = wire, ""
|
|
215
|
+
|
|
216
|
+
# Rows ###################################################################
|
|
217
|
+
|
|
218
|
+
def _item(self, inline, item, path, extra):
|
|
219
|
+
type_label = item["type"]
|
|
220
|
+
if (plugin_id := item.get("id")) is None:
|
|
221
|
+
if not inline.has_add_permission(self.request, self.existing_obj):
|
|
222
|
+
self.error(path, "No permission to add it.")
|
|
223
|
+
return
|
|
224
|
+
instance = inline.model()
|
|
225
|
+
setattr(instance, fk_name(inline), self.obj)
|
|
226
|
+
self.rows[inline].append(
|
|
227
|
+
Row(instance, path, item.get("fields") or {}, extra)
|
|
228
|
+
)
|
|
229
|
+
return
|
|
230
|
+
if (row := self.existing.get((type_label, plugin_id))) is None:
|
|
231
|
+
self.error(f"{path}.id", f"No {type_label} with this id on this object.")
|
|
232
|
+
return
|
|
233
|
+
if (type_label, plugin_id) in self.used:
|
|
234
|
+
self.error(f"{path}.id", "Used twice.")
|
|
235
|
+
return
|
|
236
|
+
self.used.add((type_label, plugin_id))
|
|
237
|
+
row.path, row.extra = path, extra
|
|
238
|
+
row.wire = item.get("fields") or {}
|
|
239
|
+
changes_something = row.wire or any(
|
|
240
|
+
getattr(row.instance, name, value) != value for name, value in extra.items()
|
|
241
|
+
)
|
|
242
|
+
if changes_something and not inline.has_change_permission(
|
|
243
|
+
self.request, self.existing_obj
|
|
244
|
+
):
|
|
245
|
+
self.error(path, "No permission to change it.")
|
|
246
|
+
|
|
247
|
+
def _delete(self, inline, row, path):
|
|
248
|
+
row.delete = True
|
|
249
|
+
if not (
|
|
250
|
+
inline.can_delete
|
|
251
|
+
and inline.has_delete_permission(self.request, self.existing_obj)
|
|
252
|
+
):
|
|
253
|
+
self.error(
|
|
254
|
+
path,
|
|
255
|
+
f"Leaves out {label(type(row.instance))} {row.instance.pk}, which"
|
|
256
|
+
" you have no permission to delete.",
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
# Formsets ###############################################################
|
|
260
|
+
|
|
261
|
+
def bind(self, target):
|
|
262
|
+
"""``(bound formsets, errors)``: the rows, bound to the admin's
|
|
263
|
+
formsets of ``target`` (the object as the form made it)"""
|
|
264
|
+
bound, errors = [], []
|
|
265
|
+
formset_classes = [
|
|
266
|
+
inline.get_formset(self.request, self.existing_obj)
|
|
267
|
+
for inline in self.inlines
|
|
268
|
+
]
|
|
269
|
+
for inline, prefix in zip(self.inlines, prefixes(formset_classes), strict=True):
|
|
270
|
+
context = self.resource.inline_context(
|
|
271
|
+
self.request, inline, self.existing_obj, self.api
|
|
272
|
+
)
|
|
273
|
+
one, bind_errors = bind_formset(
|
|
274
|
+
self.request,
|
|
275
|
+
inline,
|
|
276
|
+
target,
|
|
277
|
+
self.rows[inline],
|
|
278
|
+
context,
|
|
279
|
+
self.api.adapters.lookup(context.type),
|
|
280
|
+
prefix=prefix,
|
|
281
|
+
path="content"
|
|
282
|
+
if _is_plugin_inline(inline)
|
|
283
|
+
else f"inlines.{context.type}",
|
|
284
|
+
)
|
|
285
|
+
bound.append(one)
|
|
286
|
+
errors.extend(bind_errors)
|
|
287
|
+
return bound, errors
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _is_plugin_inline(inline):
|
|
291
|
+
return isinstance(inline, ContentEditorInline)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def validate_formsets(bound):
|
|
295
|
+
errors = []
|
|
296
|
+
for one in bound:
|
|
297
|
+
if not one.formset.is_valid():
|
|
298
|
+
errors.extend(formset_errors(one))
|
|
299
|
+
return errors
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def created_objects(bound):
|
|
303
|
+
"""``(type, id)`` of the objects the saved formsets added"""
|
|
304
|
+
return [
|
|
305
|
+
(label(type(obj)), obj.pk) for one in bound for obj in one.formset.new_objects
|
|
306
|
+
]
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def log_message(entries):
|
|
310
|
+
"""The admin's change message for ``entries``, marked as an API change"""
|
|
311
|
+
text = LogEntry(change_message=json.dumps(entries)).get_change_message()
|
|
312
|
+
return f"{text or _('No fields changed.')} {_('(Through the API.)')}"
|
feincms3_api/errors.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Errors of the content API's operations, mapped to HTTP responses by the
|
|
3
|
+
endpoints
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class APIError(Exception):
|
|
8
|
+
status = 400
|
|
9
|
+
|
|
10
|
+
def __init__(self, detail="", **extra):
|
|
11
|
+
super().__init__(detail)
|
|
12
|
+
self.detail = detail
|
|
13
|
+
self.extra = extra
|
|
14
|
+
|
|
15
|
+
def as_json(self):
|
|
16
|
+
return {"detail": self.detail, **self.extra}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class NotFoundError(APIError):
|
|
20
|
+
status = 404
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ForbiddenError(APIError):
|
|
24
|
+
status = 403
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ConflictError(APIError):
|
|
28
|
+
status = 409
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class PreconditionRequiredError(APIError):
|
|
32
|
+
status = 428
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class PreconditionFailedError(APIError):
|
|
36
|
+
status = 412
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ValidationFailedError(APIError):
|
|
40
|
+
"""Every problem of a write, each with its path"""
|
|
41
|
+
|
|
42
|
+
status = 422
|
|
43
|
+
|
|
44
|
+
def __init__(self, errors):
|
|
45
|
+
super().__init__("The data isn't valid.")
|
|
46
|
+
self.errors = errors
|
|
47
|
+
|
|
48
|
+
def as_json(self):
|
|
49
|
+
return {"detail": self.detail, "errors": self.errors}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class WireError(Exception):
|
|
53
|
+
"""A wire value a codec can't decode"""
|
feincms3_api/forms.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""
|
|
2
|
+
feincms3-forms: configured forms and their fields
|
|
3
|
+
|
|
4
|
+
The fields are plugins (proxies of one model per field type, and plugins of
|
|
5
|
+
their own); a resource for the forms only adds the form type's validation,
|
|
6
|
+
which the admin shows as messages, to ``meta.warnings``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from django.contrib.messages import constants
|
|
10
|
+
|
|
11
|
+
from feincms3_api.resources import ERROR, WARNING, ObjectResource, warning
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ConfiguredFormResource(ObjectResource):
|
|
15
|
+
"""A ``ConfiguredForm`` subclass"""
|
|
16
|
+
|
|
17
|
+
def check(self, request, obj):
|
|
18
|
+
warnings = list(super().check(request, obj))
|
|
19
|
+
if (type := obj.type) is None:
|
|
20
|
+
warnings.append(
|
|
21
|
+
warning(
|
|
22
|
+
f"The form type {obj.form_type!r} doesn't exist; the form"
|
|
23
|
+
" can't be validated.",
|
|
24
|
+
level=ERROR,
|
|
25
|
+
path="fields.form_type",
|
|
26
|
+
)
|
|
27
|
+
)
|
|
28
|
+
return warnings
|
|
29
|
+
warnings.extend(
|
|
30
|
+
warning(
|
|
31
|
+
message.message,
|
|
32
|
+
level=ERROR if message.level >= constants.ERROR else WARNING,
|
|
33
|
+
)
|
|
34
|
+
for message in type.validate(obj)
|
|
35
|
+
)
|
|
36
|
+
return warnings
|
feincms3_api/formsets.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The admin's inline formsets, bound to the API's data
|
|
3
|
+
|
|
4
|
+
A write binds every inline of the object, plugins and other inlines, to the
|
|
5
|
+
formset the admin would build (``inline.get_formset()``, the same prefix and
|
|
6
|
+
queryset), with a form for every row the admin would post: the unchanged
|
|
7
|
+
ones too, so a formset's own ``clean()`` sees all of them. Saving then goes
|
|
8
|
+
through ``save_related()`` and ``save_formset()``, as in the admin.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import dataclasses
|
|
12
|
+
|
|
13
|
+
from django.forms.formsets import DELETION_FIELD_NAME
|
|
14
|
+
|
|
15
|
+
from feincms3_api.adapters import form_errors, prepare_form
|
|
16
|
+
from feincms3_api.resources import fk_name
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclasses.dataclass
|
|
20
|
+
class Row:
|
|
21
|
+
"""One form of a formset: an existing object or a new one"""
|
|
22
|
+
|
|
23
|
+
#: The object; a new one isn't saved yet (no ``pk``)
|
|
24
|
+
instance: object
|
|
25
|
+
#: Where it is on the wire, for errors (``content.main[2]``, or ``""``)
|
|
26
|
+
path: str
|
|
27
|
+
#: The ``fields`` sent, ``None`` if it stays as it is
|
|
28
|
+
wire: dict | None = None
|
|
29
|
+
#: Form data the API sets itself (a plugin's region, ordering, depth)
|
|
30
|
+
extra: dict = dataclasses.field(default_factory=dict)
|
|
31
|
+
delete: bool = False
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def new(self):
|
|
35
|
+
return self.instance.pk is None
|
|
36
|
+
|
|
37
|
+
def fields_path(self):
|
|
38
|
+
return f"{self.path}.fields" if self.path else "fields"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclasses.dataclass
|
|
42
|
+
class BoundFormset:
|
|
43
|
+
inline: object
|
|
44
|
+
formset: object
|
|
45
|
+
rows: list
|
|
46
|
+
#: The path of errors which aren't one form's (the formset's ``clean()``)
|
|
47
|
+
path: str
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def bind_formset(request, inline, obj, rows, context, adapter, *, prefix, path):
|
|
51
|
+
"""``(BoundFormset, errors)``: ``rows`` bound to the inline's formset"""
|
|
52
|
+
change = obj.pk is not None
|
|
53
|
+
formset_class = inline.get_formset(request, obj if change else None)
|
|
54
|
+
pk_name = inline.model._meta.pk.name
|
|
55
|
+
# The admin's formsets have the existing objects first
|
|
56
|
+
rows = [row for row in rows if not row.new] + [row for row in rows if row.new]
|
|
57
|
+
initial = sum(1 for row in rows if not row.new)
|
|
58
|
+
data = {
|
|
59
|
+
f"{prefix}-TOTAL_FORMS": len(rows),
|
|
60
|
+
f"{prefix}-INITIAL_FORMS": initial,
|
|
61
|
+
f"{prefix}-MIN_NUM_FORMS": 0,
|
|
62
|
+
f"{prefix}-MAX_NUM_FORMS": len(rows),
|
|
63
|
+
}
|
|
64
|
+
errors = []
|
|
65
|
+
for index, row in enumerate(rows):
|
|
66
|
+
form_data, row_errors = adapter.form_data(
|
|
67
|
+
context,
|
|
68
|
+
row.instance,
|
|
69
|
+
row.wire or {},
|
|
70
|
+
path=row.fields_path(),
|
|
71
|
+
extra=row.extra,
|
|
72
|
+
)
|
|
73
|
+
errors.extend(row_errors)
|
|
74
|
+
for name, value in (form_data or {}).items():
|
|
75
|
+
data[f"{prefix}-{index}-{name}"] = value
|
|
76
|
+
if not row.new:
|
|
77
|
+
data[f"{prefix}-{index}-{pk_name}"] = row.instance.pk
|
|
78
|
+
if row.delete:
|
|
79
|
+
data[f"{prefix}-{index}-{DELETION_FIELD_NAME}"] = True
|
|
80
|
+
|
|
81
|
+
keep_always = {fk_name(inline)}
|
|
82
|
+
|
|
83
|
+
class APIFormSet(formset_class):
|
|
84
|
+
def _construct_form(self, i, **kwargs):
|
|
85
|
+
form = super()._construct_form(i, **kwargs)
|
|
86
|
+
row = rows[i]
|
|
87
|
+
prepare_form(form, context, keep=keep_always | set(row.extra))
|
|
88
|
+
if row.new:
|
|
89
|
+
# Sent to be created, even if all its values are defaults
|
|
90
|
+
form.empty_permitted = False
|
|
91
|
+
form.has_changed = lambda: True
|
|
92
|
+
return form
|
|
93
|
+
|
|
94
|
+
formset = APIFormSet(
|
|
95
|
+
data=data,
|
|
96
|
+
files={},
|
|
97
|
+
instance=obj,
|
|
98
|
+
prefix=prefix,
|
|
99
|
+
queryset=inline.get_queryset(request),
|
|
100
|
+
)
|
|
101
|
+
if not inline.has_change_permission(request, obj if change else None):
|
|
102
|
+
# As the admin does: view-only rows aren't validated, unless deleted
|
|
103
|
+
for form, row in zip(formset.initial_forms, rows, strict=False):
|
|
104
|
+
if not row.delete:
|
|
105
|
+
form._errors = {}
|
|
106
|
+
form.cleaned_data = form.initial
|
|
107
|
+
return BoundFormset(inline, formset, rows, path), errors
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def formset_errors(bound):
|
|
111
|
+
"""A bound formset's errors, with the paths of its rows"""
|
|
112
|
+
formset = bound.formset
|
|
113
|
+
errors = []
|
|
114
|
+
for form, row in zip(formset.forms, bound.rows, strict=True):
|
|
115
|
+
if row.delete:
|
|
116
|
+
continue
|
|
117
|
+
errors.extend(form_errors(form, row.fields_path()))
|
|
118
|
+
errors.extend(
|
|
119
|
+
{"path": bound.path, "message": str(message)}
|
|
120
|
+
for message in formset.non_form_errors()
|
|
121
|
+
)
|
|
122
|
+
return errors
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def prefixes(formset_classes):
|
|
126
|
+
"""The admin's formset prefixes, numbered where two are the same"""
|
|
127
|
+
seen = {}
|
|
128
|
+
result = []
|
|
129
|
+
for formset_class in formset_classes:
|
|
130
|
+
prefix = formset_class.get_default_prefix()
|
|
131
|
+
seen[prefix] = seen.get(prefix, 0) + 1
|
|
132
|
+
if seen[prefix] != 1 or not prefix:
|
|
133
|
+
prefix = f"{prefix}-{seen[prefix]}"
|
|
134
|
+
result.append(prefix)
|
|
135
|
+
return result
|