django-admin-api-mcp 0.1.0a2__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.
- admin_api/__init__.py +9 -0
- admin_api/actions.py +115 -0
- admin_api/admin.py +108 -0
- admin_api/apps.py +9 -0
- admin_api/auth.py +62 -0
- admin_api/changelist.py +194 -0
- admin_api/checks.py +35 -0
- admin_api/contrib/__init__.py +1 -0
- admin_api/contrib/subadmin.py +37 -0
- admin_api/custom_views.py +458 -0
- admin_api/decorators.py +26 -0
- admin_api/deletion.py +54 -0
- admin_api/detail.py +127 -0
- admin_api/encoders.py +59 -0
- admin_api/errors.py +44 -0
- admin_api/jsonschema.py +216 -0
- admin_api/management/__init__.py +0 -0
- admin_api/management/commands/__init__.py +0 -0
- admin_api/management/commands/create_api_token.py +40 -0
- admin_api/management/commands/mcp_serve.py +86 -0
- admin_api/mcp/__init__.py +7 -0
- admin_api/mcp/bridge.py +71 -0
- admin_api/mcp/confirm.py +54 -0
- admin_api/mcp/handlers.py +665 -0
- admin_api/mcp/server.py +75 -0
- admin_api/mcp/sites.py +198 -0
- admin_api/mcp/stdio.py +53 -0
- admin_api/mcp/tools.py +84 -0
- admin_api/mcp/views.py +69 -0
- admin_api/middleware.py +18 -0
- admin_api/migrations/0001_initial.py +40 -0
- admin_api/migrations/__init__.py +0 -0
- admin_api/mixins.py +144 -0
- admin_api/models.py +113 -0
- admin_api/nested.py +122 -0
- admin_api/resolver.py +95 -0
- admin_api/scopes.py +121 -0
- admin_api/services.py +423 -0
- admin_api/sites.py +225 -0
- admin_api/views/__init__.py +0 -0
- admin_api/views/changelist.py +50 -0
- admin_api/views/custom.py +31 -0
- admin_api/views/detail.py +39 -0
- admin_api/views/nested.py +70 -0
- admin_api/views/registry.py +15 -0
- admin_api/writes.py +479 -0
- django_admin_api_mcp-0.1.0a2.dist-info/METADATA +274 -0
- django_admin_api_mcp-0.1.0a2.dist-info/RECORD +49 -0
- django_admin_api_mcp-0.1.0a2.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,458 @@
|
|
|
1
|
+
"""Custom admin views in the API and MCP: ``@admin_api.view``.
|
|
2
|
+
|
|
3
|
+
A custom admin page (a statement, a stock balance, "post this invoice"…) usually has two
|
|
4
|
+
parts: computing data and rendering HTML. Put the first part in a ModelAdmin method decorated
|
|
5
|
+
with :func:`admin_api.view`; the HTML view and the API then share it::
|
|
6
|
+
|
|
7
|
+
class ClientAdmin(admin.ModelAdmin):
|
|
8
|
+
@admin_api.view(detail=True, params=StatementForm, description="Account statement.")
|
|
9
|
+
def statement(self, request, obj, date_from=None, date_to=None):
|
|
10
|
+
return {...} # JSON-able (models, dates, Decimals are encoded)
|
|
11
|
+
|
|
12
|
+
* ``detail=True``: runs on one object, ``method(request, obj, **params)``;
|
|
13
|
+
REST ``/v1/<app>/<model>/<pk>/views/<name>/``.
|
|
14
|
+
``detail=False``: ``method(request, **params)``; REST ``/v1/<app>/<model>/views/<name>/``.
|
|
15
|
+
* ``params``: a Django ``Form`` class (validated, ``cleaned_data`` passed as keyword arguments,
|
|
16
|
+
JSON Schema generated from it) or a dict of JSON Schema properties (with ``required=[...]``).
|
|
17
|
+
* ``permissions``: like ``@admin.action(permissions=...)``: every ``has_<perm>_permission`` must
|
|
18
|
+
pass (``view`` means view-or-change; with ``detail=True`` the object is passed for the
|
|
19
|
+
built-in ones). Token scopes apply to the built-in ones.
|
|
20
|
+
* ``writes``: defaults to ``True`` when ``permissions`` asks for more than ``view``
|
|
21
|
+
(``writes=True`` with the default permissions means ``permissions=["change"]``). Write views
|
|
22
|
+
are POST only, run in a transaction, need a write scope on tokens, are hidden from read-only
|
|
23
|
+
MCP sites and support ``dry_run`` in MCP. Read views accept GET (query string) and POST (JSON).
|
|
24
|
+
* MCP: listed in ``list_models`` and ``describe_model``, run with the ``run_view`` tool;
|
|
25
|
+
``mcp_tool="name"`` also publishes the view as its own MCP tool (top-level admins only).
|
|
26
|
+
* ``api_enabled=False`` hides the view from both surfaces, ``mcp_enabled=False`` from MCP only.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import copy
|
|
32
|
+
from dataclasses import dataclass, field
|
|
33
|
+
|
|
34
|
+
from django import forms
|
|
35
|
+
from django.core.exceptions import ImproperlyConfigured, ValidationError
|
|
36
|
+
from django.core.exceptions import PermissionDenied as DjangoPermissionDenied
|
|
37
|
+
from django.db import router, transaction
|
|
38
|
+
from django.http import HttpResponseBase, QueryDict
|
|
39
|
+
from django.utils.dateparse import parse_date, parse_datetime, parse_time
|
|
40
|
+
|
|
41
|
+
from . import scopes
|
|
42
|
+
from .encoders import encode_value
|
|
43
|
+
from .errors import ApiError, NotFound, PermissionDeniedError
|
|
44
|
+
|
|
45
|
+
VIEW_ATTR = "admin_api_view"
|
|
46
|
+
READ_METHODS = ("GET", "POST")
|
|
47
|
+
WRITE_METHODS = ("POST",)
|
|
48
|
+
# Reserved keys of a promoted MCP tool's arguments (params are flattened next to them).
|
|
49
|
+
TOOL_RESERVED = frozenset({"pk", "dry_run", "confirm_token"})
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class InvalidParams(ApiError):
|
|
53
|
+
status = 400
|
|
54
|
+
code = "invalid_params"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class ViewNotSupported(ApiError):
|
|
58
|
+
status = 400
|
|
59
|
+
code = "view_not_supported"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True)
|
|
63
|
+
class ViewSpec:
|
|
64
|
+
"""What ``@admin_api.view`` attaches to a ModelAdmin method."""
|
|
65
|
+
|
|
66
|
+
name: str
|
|
67
|
+
attname: str # the method name on the admin
|
|
68
|
+
detail: bool = False
|
|
69
|
+
permissions: tuple = ("view",)
|
|
70
|
+
writes: bool = False
|
|
71
|
+
form_class: type | None = None
|
|
72
|
+
properties: dict = field(default_factory=dict) # JSON Schema properties, when not a form
|
|
73
|
+
required: tuple = ()
|
|
74
|
+
title: str = ""
|
|
75
|
+
description: str = ""
|
|
76
|
+
output_schema: dict | None = None
|
|
77
|
+
api_enabled: bool = True
|
|
78
|
+
mcp_enabled: bool = True
|
|
79
|
+
mcp_tool: str | None = None
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def methods(self) -> tuple:
|
|
83
|
+
return WRITE_METHODS if self.writes else READ_METHODS
|
|
84
|
+
|
|
85
|
+
def params_schema(self) -> dict:
|
|
86
|
+
"""JSON Schema (object) of the parameters."""
|
|
87
|
+
if self.form_class is not None:
|
|
88
|
+
from .jsonschema import form_object_schema
|
|
89
|
+
|
|
90
|
+
return form_object_schema(self.form_class, required=True)
|
|
91
|
+
out = {"type": "object", "properties": dict(self.properties), "additionalProperties": False}
|
|
92
|
+
if self.required:
|
|
93
|
+
out["required"] = list(self.required)
|
|
94
|
+
return out
|
|
95
|
+
|
|
96
|
+
def describe(self) -> dict:
|
|
97
|
+
out = {
|
|
98
|
+
"name": self.name,
|
|
99
|
+
"title": self.title,
|
|
100
|
+
"description": self.description,
|
|
101
|
+
"detail": self.detail,
|
|
102
|
+
"writes": self.writes,
|
|
103
|
+
"permissions": list(self.permissions),
|
|
104
|
+
"params_schema": self.params_schema(),
|
|
105
|
+
}
|
|
106
|
+
if self.output_schema is not None:
|
|
107
|
+
out["output_schema"] = self.output_schema
|
|
108
|
+
if self.mcp_tool:
|
|
109
|
+
out["mcp_tool"] = self.mcp_tool
|
|
110
|
+
return out
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def view(
|
|
114
|
+
function=None,
|
|
115
|
+
*,
|
|
116
|
+
name: str | None = None,
|
|
117
|
+
detail: bool = False,
|
|
118
|
+
permissions=("view",),
|
|
119
|
+
writes: bool | None = None,
|
|
120
|
+
params=None,
|
|
121
|
+
required=(),
|
|
122
|
+
title: str | None = None,
|
|
123
|
+
description: str | None = None,
|
|
124
|
+
output_schema: dict | None = None,
|
|
125
|
+
api_enabled: bool = True,
|
|
126
|
+
mcp_enabled: bool = True,
|
|
127
|
+
mcp_tool: str | None = None,
|
|
128
|
+
):
|
|
129
|
+
"""Expose a ModelAdmin method as a custom view in the REST API and MCP. See the module docs."""
|
|
130
|
+
|
|
131
|
+
def decorator(func):
|
|
132
|
+
permissions_ = (permissions,) if isinstance(permissions, str) else tuple(permissions)
|
|
133
|
+
if writes and permissions_ == ("view",):
|
|
134
|
+
permissions_ = ("change",) # a write view does not run on view permission alone
|
|
135
|
+
if not permissions_:
|
|
136
|
+
raise ImproperlyConfigured(f"@admin_api.view {func.__name__}: permissions cannot be empty.")
|
|
137
|
+
form_class, properties = None, {}
|
|
138
|
+
if isinstance(params, type) and issubclass(params, forms.BaseForm):
|
|
139
|
+
form_class = params
|
|
140
|
+
if required:
|
|
141
|
+
raise ImproperlyConfigured(f"@admin_api.view {func.__name__}: 'required' comes from the form.")
|
|
142
|
+
elif isinstance(params, dict):
|
|
143
|
+
properties = dict(params)
|
|
144
|
+
unknown = set(required) - set(properties)
|
|
145
|
+
if unknown:
|
|
146
|
+
raise ImproperlyConfigured(
|
|
147
|
+
f"@admin_api.view {func.__name__}: required {sorted(unknown)} not in params."
|
|
148
|
+
)
|
|
149
|
+
elif params is not None:
|
|
150
|
+
raise ImproperlyConfigured(
|
|
151
|
+
f"@admin_api.view {func.__name__}: params must be a Form class or a dict of JSON Schema properties."
|
|
152
|
+
)
|
|
153
|
+
names = set(form_class.base_fields) if form_class is not None else set(properties)
|
|
154
|
+
if mcp_tool and names & TOOL_RESERVED:
|
|
155
|
+
raise ImproperlyConfigured(
|
|
156
|
+
f"@admin_api.view {func.__name__}: params {sorted(names & TOOL_RESERVED)} clash with the arguments "
|
|
157
|
+
f"of the MCP tool {mcp_tool!r}; rename them."
|
|
158
|
+
)
|
|
159
|
+
doc = (func.__doc__ or "").strip()
|
|
160
|
+
spec = ViewSpec(
|
|
161
|
+
name=name or func.__name__,
|
|
162
|
+
attname=func.__name__,
|
|
163
|
+
detail=detail,
|
|
164
|
+
permissions=permissions_,
|
|
165
|
+
writes=(set(permissions_) != {"view"}) if writes is None else bool(writes),
|
|
166
|
+
form_class=form_class,
|
|
167
|
+
properties=properties,
|
|
168
|
+
required=tuple(required),
|
|
169
|
+
title=str(title or (name or func.__name__).replace("_", " ").capitalize()),
|
|
170
|
+
description=str(description or doc),
|
|
171
|
+
output_schema=output_schema,
|
|
172
|
+
api_enabled=api_enabled,
|
|
173
|
+
mcp_enabled=mcp_enabled,
|
|
174
|
+
mcp_tool=mcp_tool,
|
|
175
|
+
)
|
|
176
|
+
setattr(func, VIEW_ATTR, spec)
|
|
177
|
+
return func
|
|
178
|
+
|
|
179
|
+
if function is None:
|
|
180
|
+
return decorator
|
|
181
|
+
return decorator(function)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
# --------------------------------------------------------------------------------------------
|
|
185
|
+
# discovery
|
|
186
|
+
# --------------------------------------------------------------------------------------------
|
|
187
|
+
_class_cache: dict = {}
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def declared_views(model_admin) -> dict[str, ViewSpec]:
|
|
191
|
+
"""``{name: spec}`` of the views declared on the admin's class (subclasses override)."""
|
|
192
|
+
cls = type(model_admin)
|
|
193
|
+
cached = _class_cache.get(cls)
|
|
194
|
+
if cached is None:
|
|
195
|
+
cached = {}
|
|
196
|
+
for klass in reversed(cls.__mro__):
|
|
197
|
+
for attr, value in vars(klass).items():
|
|
198
|
+
spec = getattr(value, VIEW_ATTR, None)
|
|
199
|
+
if isinstance(spec, ViewSpec):
|
|
200
|
+
# an override without the decorator removes the view
|
|
201
|
+
cached = {n: s for n, s in cached.items() if s.attname != attr}
|
|
202
|
+
cached[spec.name] = spec
|
|
203
|
+
elif attr in {s.attname for s in cached.values()}:
|
|
204
|
+
cached = {n: s for n, s in cached.items() if s.attname != attr}
|
|
205
|
+
_class_cache[cls] = cached
|
|
206
|
+
return cached
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def has_view_permission(model_admin, request, spec: ViewSpec, obj=None) -> bool:
|
|
210
|
+
"""Every permission of ``spec`` (and the token scopes of the built-in ones)."""
|
|
211
|
+
for perm in spec.permissions:
|
|
212
|
+
if perm == "view":
|
|
213
|
+
ok = model_admin.has_view_or_change_permission(request, obj)
|
|
214
|
+
elif perm == "add":
|
|
215
|
+
ok = model_admin.has_add_permission(request)
|
|
216
|
+
elif perm in ("change", "delete"):
|
|
217
|
+
ok = getattr(model_admin, f"has_{perm}_permission")(request, obj)
|
|
218
|
+
else: # custom, like admin actions: has_<perm>_permission(request)
|
|
219
|
+
checker = getattr(model_admin, f"has_{perm}_permission", None)
|
|
220
|
+
if checker is None:
|
|
221
|
+
raise ImproperlyConfigured(
|
|
222
|
+
f"{type(model_admin).__name__} has no has_{perm}_permission() for view {spec.name!r}."
|
|
223
|
+
)
|
|
224
|
+
ok = checker(request)
|
|
225
|
+
if not ok:
|
|
226
|
+
return False
|
|
227
|
+
return all(scopes.request_allows(request, model_admin.opts, op) for op in scope_ops(spec))
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def scope_ops(spec: ViewSpec) -> set:
|
|
231
|
+
"""Token scope operations a view needs: its built-in permissions; ``change`` for a write view
|
|
232
|
+
that only names custom ones (a view-only token never runs a write)."""
|
|
233
|
+
ops = {p for p in spec.permissions if p in scopes.OPS}
|
|
234
|
+
if spec.writes and not ops - {"view"}:
|
|
235
|
+
ops.add("change")
|
|
236
|
+
return ops
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def available_views(model_admin, request, *, mcp: bool = False, read_only: bool = False) -> list[ViewSpec]:
|
|
240
|
+
"""The views ``request.user`` may run on this admin (detail views checked without an object)."""
|
|
241
|
+
out = []
|
|
242
|
+
for spec in declared_views(model_admin).values():
|
|
243
|
+
if not spec.api_enabled or (mcp and not spec.mcp_enabled) or (read_only and spec.writes):
|
|
244
|
+
continue
|
|
245
|
+
if has_view_permission(model_admin, request, spec):
|
|
246
|
+
out.append(spec)
|
|
247
|
+
return out
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def get_view(model_admin, request, name: str, *, mcp: bool = False, read_only: bool = False) -> ViewSpec:
|
|
251
|
+
spec = declared_views(model_admin).get(name)
|
|
252
|
+
if spec is None or not spec.api_enabled or (mcp and not spec.mcp_enabled) or (read_only and spec.writes):
|
|
253
|
+
raise NotFound(f"No view {name!r} on {model_admin.opts.app_label}.{model_admin.opts.model_name}.")
|
|
254
|
+
return spec
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
# --------------------------------------------------------------------------------------------
|
|
258
|
+
# parameters
|
|
259
|
+
# --------------------------------------------------------------------------------------------
|
|
260
|
+
_TYPES = {
|
|
261
|
+
"string": lambda v: isinstance(v, str),
|
|
262
|
+
"integer": lambda v: isinstance(v, int) and not isinstance(v, bool),
|
|
263
|
+
"number": lambda v: isinstance(v, (int, float)) and not isinstance(v, bool),
|
|
264
|
+
"boolean": lambda v: isinstance(v, bool),
|
|
265
|
+
"array": lambda v: isinstance(v, list),
|
|
266
|
+
"object": lambda v: isinstance(v, dict),
|
|
267
|
+
"null": lambda v: v is None,
|
|
268
|
+
}
|
|
269
|
+
_FORMATS = {"date": parse_date, "date-time": parse_datetime, "time": parse_time}
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _types(schema) -> list:
|
|
273
|
+
t = schema.get("type")
|
|
274
|
+
return t if isinstance(t, list) else ([t] if t else [])
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _from_query(raw: list[str], schema: dict):
|
|
278
|
+
"""Query-string values (strings) → the JSON type the schema asks for."""
|
|
279
|
+
types = _types(schema)
|
|
280
|
+
if "array" in types:
|
|
281
|
+
items = schema.get("items") or {}
|
|
282
|
+
return [_from_query([v], items) for v in raw]
|
|
283
|
+
value = raw[-1]
|
|
284
|
+
if value == "" and "null" in types:
|
|
285
|
+
return None
|
|
286
|
+
for t in types:
|
|
287
|
+
try:
|
|
288
|
+
if t == "integer":
|
|
289
|
+
return int(value)
|
|
290
|
+
if t == "number":
|
|
291
|
+
return float(value) if any(c in value for c in ".eE") else int(value)
|
|
292
|
+
if t == "boolean" and value.lower() in ("1", "true", "yes", "on", "0", "false", "no", "off"):
|
|
293
|
+
return value.lower() in ("1", "true", "yes", "on")
|
|
294
|
+
except ValueError:
|
|
295
|
+
continue
|
|
296
|
+
return value
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _check_value(name: str, value, schema: dict, errors: dict):
|
|
300
|
+
types = _types(schema)
|
|
301
|
+
if types and not any(_TYPES.get(t, lambda v: True)(value) for t in types):
|
|
302
|
+
errors.setdefault(name, []).append(f"Expected {' or '.join(types)}.")
|
|
303
|
+
return value
|
|
304
|
+
if "enum" in schema and value not in schema["enum"]:
|
|
305
|
+
errors.setdefault(name, []).append(f"Must be one of: {', '.join(map(str, schema['enum']))}.")
|
|
306
|
+
return value
|
|
307
|
+
if isinstance(value, list) and "items" in schema:
|
|
308
|
+
return [_check_value(f"{name}[{i}]", v, schema["items"], errors) for i, v in enumerate(value)]
|
|
309
|
+
parser = _FORMATS.get(schema.get("format"))
|
|
310
|
+
if parser is not None and isinstance(value, str):
|
|
311
|
+
try:
|
|
312
|
+
parsed = parser(value)
|
|
313
|
+
except ValueError:
|
|
314
|
+
parsed = None
|
|
315
|
+
if parsed is None:
|
|
316
|
+
errors.setdefault(name, []).append(f"Not a valid {schema['format']}.")
|
|
317
|
+
return parsed
|
|
318
|
+
for key, test, msg in (
|
|
319
|
+
("minimum", lambda v, m: v >= m, "at least"),
|
|
320
|
+
("maximum", lambda v, m: v <= m, "at most"),
|
|
321
|
+
):
|
|
322
|
+
if key in schema and isinstance(value, (int, float)) and not test(value, schema[key]):
|
|
323
|
+
errors.setdefault(name, []).append(f"Must be {msg} {schema[key]}.")
|
|
324
|
+
return value
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _clean_schema_params(spec: ViewSpec, data: dict) -> dict:
|
|
328
|
+
errors: dict = {}
|
|
329
|
+
for key in data:
|
|
330
|
+
if key not in spec.properties:
|
|
331
|
+
errors.setdefault(key, []).append("Unknown parameter.")
|
|
332
|
+
out = {}
|
|
333
|
+
for key, schema in spec.properties.items():
|
|
334
|
+
if key in data:
|
|
335
|
+
out[key] = _check_value(key, data[key], schema, errors)
|
|
336
|
+
elif key in spec.required:
|
|
337
|
+
errors.setdefault(key, []).append("This parameter is required.")
|
|
338
|
+
elif "default" in schema:
|
|
339
|
+
out[key] = _check_value(key, schema["default"], schema, errors)
|
|
340
|
+
if errors:
|
|
341
|
+
raise InvalidParams("Invalid parameters.", fields=errors)
|
|
342
|
+
return out
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _clean_form_params(spec: ViewSpec, request, data) -> dict:
|
|
346
|
+
from .writes import field_post_values
|
|
347
|
+
|
|
348
|
+
base_fields = spec.form_class.base_fields
|
|
349
|
+
if isinstance(data, QueryDict):
|
|
350
|
+
query = data
|
|
351
|
+
unknown = [k for k in query if k not in base_fields and not any(k.startswith(f"{f}_") for f in base_fields)]
|
|
352
|
+
else:
|
|
353
|
+
query = QueryDict(mutable=True)
|
|
354
|
+
unknown = [k for k in data if k not in base_fields]
|
|
355
|
+
for key, value in data.items():
|
|
356
|
+
if key in base_fields:
|
|
357
|
+
for post_key, values in field_post_values(key, base_fields[key], value).items():
|
|
358
|
+
query.setlist(post_key, values)
|
|
359
|
+
if unknown:
|
|
360
|
+
raise InvalidParams("Invalid parameters.", fields={k: ["Unknown parameter."] for k in unknown})
|
|
361
|
+
form = spec.form_class(data=query)
|
|
362
|
+
if not form.is_valid():
|
|
363
|
+
errors = {k: [str(m) for m in v] for k, v in form.errors.items()}
|
|
364
|
+
raise InvalidParams("Invalid parameters.", fields=errors)
|
|
365
|
+
return dict(form.cleaned_data)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def clean_params(spec: ViewSpec, request, data) -> dict:
|
|
369
|
+
"""Validate ``data`` (a JSON object, or the query string of a GET as a ``QueryDict``) into the
|
|
370
|
+
keyword arguments of the view method."""
|
|
371
|
+
if spec.form_class is not None:
|
|
372
|
+
return _clean_form_params(spec, request, data)
|
|
373
|
+
if isinstance(data, QueryDict):
|
|
374
|
+
data = {k: _from_query(data.getlist(k), spec.properties.get(k, {})) for k in data}
|
|
375
|
+
return _clean_schema_params(spec, data)
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
# --------------------------------------------------------------------------------------------
|
|
379
|
+
# running
|
|
380
|
+
# --------------------------------------------------------------------------------------------
|
|
381
|
+
def run_view(model_admin, request, name: str, *, object_id=None, data=None, mcp=False, read_only=False) -> dict:
|
|
382
|
+
"""Check permissions, validate ``data`` and run the view. Returns
|
|
383
|
+
``{"view", "result", "messages"}`` (plus ``"pk"`` for a detail view)."""
|
|
384
|
+
from .services import get_object
|
|
385
|
+
from .writes import capture_messages
|
|
386
|
+
|
|
387
|
+
spec = get_view(model_admin, request, name, mcp=mcp, read_only=read_only)
|
|
388
|
+
obj = None
|
|
389
|
+
if spec.detail:
|
|
390
|
+
if object_id is None:
|
|
391
|
+
raise InvalidParams(f"View {name!r} runs on one object: give its pk.")
|
|
392
|
+
obj = get_object(model_admin, request, object_id)
|
|
393
|
+
elif object_id is not None:
|
|
394
|
+
raise InvalidParams(f"View {name!r} does not run on an object: no pk expected.")
|
|
395
|
+
if not has_view_permission(model_admin, request, spec, obj):
|
|
396
|
+
raise PermissionDeniedError()
|
|
397
|
+
for op in scope_ops(spec): # second line of defense, like the other services
|
|
398
|
+
scopes.check(request, model_admin.opts, op)
|
|
399
|
+
kwargs = clean_params(spec, request, data if data is not None else {})
|
|
400
|
+
|
|
401
|
+
# a copy, so messages raised by the view are captured and returned instead of stored
|
|
402
|
+
request = copy.copy(request)
|
|
403
|
+
storage = capture_messages(request)
|
|
404
|
+
method = getattr(model_admin, spec.attname)
|
|
405
|
+
args = (request, obj) if spec.detail else (request,)
|
|
406
|
+
try:
|
|
407
|
+
if spec.writes:
|
|
408
|
+
with transaction.atomic(using=router.db_for_write(model_admin.model)):
|
|
409
|
+
result = method(*args, **kwargs)
|
|
410
|
+
if isinstance(result, HttpResponseBase):
|
|
411
|
+
transaction.set_rollback(True)
|
|
412
|
+
else:
|
|
413
|
+
result = method(*args, **kwargs)
|
|
414
|
+
except DjangoPermissionDenied as exc:
|
|
415
|
+
raise PermissionDeniedError(str(exc) or None) from exc
|
|
416
|
+
except ValidationError as exc:
|
|
417
|
+
raise ApiError(
|
|
418
|
+
"; ".join(exc.messages), status=400, code="validation_failed", non_field_errors=exc.messages
|
|
419
|
+
) from exc
|
|
420
|
+
if isinstance(result, HttpResponseBase):
|
|
421
|
+
raise ViewNotSupported(
|
|
422
|
+
f"View {name!r} returned a page/file; nothing was changed. Return JSON-able data from the "
|
|
423
|
+
"@admin_api.view method and render it in your HTML view instead."
|
|
424
|
+
)
|
|
425
|
+
out = {"view": spec.name}
|
|
426
|
+
if spec.detail:
|
|
427
|
+
out["pk"] = encode_value(obj.pk)
|
|
428
|
+
out["result"] = encode_value(result)
|
|
429
|
+
messages = storage.captured()
|
|
430
|
+
if messages:
|
|
431
|
+
out["messages"] = messages
|
|
432
|
+
return out
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def view_url(spec: ViewSpec, base_url: str | None, pk=None) -> str | None:
|
|
436
|
+
"""REST url of a view under the changelist url ``base_url``."""
|
|
437
|
+
if base_url is None:
|
|
438
|
+
return None
|
|
439
|
+
if spec.detail:
|
|
440
|
+
if pk is None:
|
|
441
|
+
return None
|
|
442
|
+
from django.contrib.admin.utils import quote
|
|
443
|
+
|
|
444
|
+
return f"{base_url}{quote(str(pk))}/views/{spec.name}/"
|
|
445
|
+
return f"{base_url}views/{spec.name}/"
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
__all__ = [
|
|
449
|
+
"InvalidParams",
|
|
450
|
+
"ViewNotSupported",
|
|
451
|
+
"ViewSpec",
|
|
452
|
+
"available_views",
|
|
453
|
+
"clean_params",
|
|
454
|
+
"declared_views",
|
|
455
|
+
"get_view",
|
|
456
|
+
"run_view",
|
|
457
|
+
"view",
|
|
458
|
+
]
|
admin_api/decorators.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from django.contrib import admin
|
|
4
|
+
|
|
5
|
+
API_DISPLAY_ATTR = "admin_api_display"
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def display(function=None, *, boolean=None, ordering=None, description=None, empty_value=None):
|
|
9
|
+
"""Like ``@admin.display`` and also marks the callable as safe to expose in the API.
|
|
10
|
+
|
|
11
|
+
Callables in ``list_display`` are left out of the API unless they are listed in
|
|
12
|
+
``api_list_display`` or decorated with this.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def decorator(func):
|
|
16
|
+
func = admin.display(boolean=boolean, ordering=ordering, description=description, empty_value=empty_value)(func)
|
|
17
|
+
setattr(func, API_DISPLAY_ATTR, True)
|
|
18
|
+
return func
|
|
19
|
+
|
|
20
|
+
if function is None:
|
|
21
|
+
return decorator
|
|
22
|
+
return decorator(function)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def is_api_display(func) -> bool:
|
|
26
|
+
return bool(getattr(func, API_DISPLAY_ATTR, False))
|
admin_api/deletion.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import html
|
|
4
|
+
|
|
5
|
+
from django.db import router, transaction
|
|
6
|
+
from django.utils.html import strip_tags
|
|
7
|
+
|
|
8
|
+
from .encoders import encode_value
|
|
9
|
+
from .errors import ApiError, PermissionDeniedError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Protected(ApiError):
|
|
13
|
+
status = 409
|
|
14
|
+
code = "protected"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _text(value):
|
|
18
|
+
if isinstance(value, (list, tuple)):
|
|
19
|
+
return [_text(v) for v in value]
|
|
20
|
+
return html.unescape(strip_tags(str(value)))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def delete_preview(model_admin, request, obj) -> dict:
|
|
24
|
+
to_delete, model_count, perms_needed, protected = model_admin.get_deleted_objects([obj], request)
|
|
25
|
+
return {
|
|
26
|
+
"object": encode_value(obj),
|
|
27
|
+
"to_delete": _text(to_delete),
|
|
28
|
+
"model_count": {str(k): v for k, v in model_count.items()},
|
|
29
|
+
"perms_needed": sorted(str(p) for p in perms_needed),
|
|
30
|
+
"protected": _text(list(protected)),
|
|
31
|
+
"can_delete": not perms_needed and not protected,
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _log_deletion(model_admin, request, obj):
|
|
36
|
+
if hasattr(model_admin, "log_deletions"): # Django >= 5.1
|
|
37
|
+
model_admin.log_deletions(request, [obj])
|
|
38
|
+
else: # pragma: no cover - Django < 5.1
|
|
39
|
+
model_admin.log_deletion(request, obj, str(obj))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def delete_object(model_admin, request, obj) -> dict:
|
|
43
|
+
preview = delete_preview(model_admin, request, obj)
|
|
44
|
+
if preview["protected"]:
|
|
45
|
+
raise Protected("Related objects are protected.", protected=preview["protected"])
|
|
46
|
+
if preview["perms_needed"]:
|
|
47
|
+
raise PermissionDeniedError(
|
|
48
|
+
"Missing delete permission on related objects.", perms_needed=preview["perms_needed"]
|
|
49
|
+
)
|
|
50
|
+
deleted = encode_value(obj)
|
|
51
|
+
with transaction.atomic(using=router.db_for_write(model_admin.model)):
|
|
52
|
+
_log_deletion(model_admin, request, obj)
|
|
53
|
+
model_admin.delete_model(request, obj)
|
|
54
|
+
return deleted
|
admin_api/detail.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Serialize one object, and its inlines, the way the admin change form shows it."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from django.contrib.admin.utils import flatten_fieldsets, lookup_field
|
|
6
|
+
from django.core.exceptions import FieldDoesNotExist
|
|
7
|
+
|
|
8
|
+
from .decorators import is_api_display
|
|
9
|
+
from .encoders import encode_value
|
|
10
|
+
from .resolver import resolve
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _model_field(model, name):
|
|
14
|
+
if not isinstance(name, str):
|
|
15
|
+
return None
|
|
16
|
+
try:
|
|
17
|
+
return model._meta.get_field(name)
|
|
18
|
+
except FieldDoesNotExist:
|
|
19
|
+
return None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def field_value(obj, field):
|
|
23
|
+
if field.many_to_many:
|
|
24
|
+
return [encode_value(o) for o in getattr(obj, field.name).all()]
|
|
25
|
+
if field.is_relation and (field.many_to_one or field.one_to_one) and field.concrete:
|
|
26
|
+
return encode_value(getattr(obj, field.name))
|
|
27
|
+
return encode_value(field.value_from_object(obj))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _name_key(name):
|
|
31
|
+
return name if isinstance(name, str) else getattr(name, "__name__", repr(name))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def detail_fields(model_admin, request, obj) -> tuple[list, bool]:
|
|
35
|
+
"""Return (field names, explicit). Explicit = from ``api_detail_fields`` / ``get_api_detail_fields``."""
|
|
36
|
+
explicit = resolve(model_admin, "detail_fields", request, obj)
|
|
37
|
+
if explicit is not None:
|
|
38
|
+
return list(explicit), True
|
|
39
|
+
return flatten_fieldsets(model_admin.get_fieldsets(request, obj)), False
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def serialize_values(model_admin, obj, names, explicit) -> dict:
|
|
43
|
+
model = type(obj)
|
|
44
|
+
out = {}
|
|
45
|
+
for name in names:
|
|
46
|
+
field = _model_field(model, name)
|
|
47
|
+
if field is not None:
|
|
48
|
+
out[name] = field_value(obj, field)
|
|
49
|
+
continue
|
|
50
|
+
func = name if callable(name) else getattr(model_admin, name, None) or getattr(model, name, None)
|
|
51
|
+
if explicit or is_api_display(func):
|
|
52
|
+
_f, _attr, value = lookup_field(name, obj, model_admin)
|
|
53
|
+
out[_name_key(name)] = encode_value(value)
|
|
54
|
+
return out
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def inline_prefixes(model_admin, request, obj, change):
|
|
58
|
+
"""``[(prefix, FormSet, inline)]`` with the same prefix rules as ``ModelAdmin._create_formsets``."""
|
|
59
|
+
out = []
|
|
60
|
+
prefixes = {}
|
|
61
|
+
args = [request, obj] if change else [request]
|
|
62
|
+
for FormSet, inline in model_admin.get_formsets_with_inlines(*args):
|
|
63
|
+
prefix = FormSet.get_default_prefix()
|
|
64
|
+
prefixes[prefix] = prefixes.get(prefix, 0) + 1
|
|
65
|
+
if prefixes[prefix] != 1 or not prefix:
|
|
66
|
+
prefix = f"{prefix}-{prefixes[prefix]}"
|
|
67
|
+
out.append((prefix, FormSet, inline))
|
|
68
|
+
return out
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def inline_queryset(FormSet, inline, request, obj):
|
|
72
|
+
qs = inline.get_queryset(request)
|
|
73
|
+
fk = getattr(FormSet, "fk", None)
|
|
74
|
+
if fk is not None:
|
|
75
|
+
return qs.filter(**{fk.name: obj})
|
|
76
|
+
ct_field = getattr(FormSet, "ct_field", None) # generic inlines
|
|
77
|
+
if ct_field is not None:
|
|
78
|
+
from django.contrib.contenttypes.models import ContentType
|
|
79
|
+
|
|
80
|
+
ct = ContentType.objects.get_for_model(obj, for_concrete_model=FormSet.for_concrete_model)
|
|
81
|
+
return qs.filter(**{ct_field.name: ct, FormSet.ct_fk_field.name: obj.pk})
|
|
82
|
+
return qs.none()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def inline_field_names(FormSet, inline, request, obj) -> list:
|
|
86
|
+
names = flatten_fieldsets(inline.get_fieldsets(request, obj))
|
|
87
|
+
excluded = set()
|
|
88
|
+
fk = getattr(FormSet, "fk", None)
|
|
89
|
+
if fk is not None:
|
|
90
|
+
excluded.add(fk.name)
|
|
91
|
+
return [n for n in names if n not in excluded]
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def serialize_inlines(model_admin, request, obj) -> dict:
|
|
95
|
+
out = {}
|
|
96
|
+
for prefix, FormSet, inline in inline_prefixes(model_admin, request, obj, change=True):
|
|
97
|
+
names = inline_field_names(FormSet, inline, request, obj)
|
|
98
|
+
qs = inline_queryset(FormSet, inline, request, obj)
|
|
99
|
+
related = [n for n in names if (f := _model_field(qs.model, n)) is not None and f.many_to_one]
|
|
100
|
+
many = [n for n in names if (f := _model_field(qs.model, n)) is not None and f.many_to_many]
|
|
101
|
+
if related:
|
|
102
|
+
qs = qs.select_related(*related)
|
|
103
|
+
if many:
|
|
104
|
+
qs = qs.prefetch_related(*many)
|
|
105
|
+
if not qs.query.order_by and not qs.ordered:
|
|
106
|
+
qs = qs.order_by("pk")
|
|
107
|
+
out[prefix] = [
|
|
108
|
+
{"pk": encode_value(row.pk), **serialize_values(inline, row, names, explicit=False)} for row in qs
|
|
109
|
+
]
|
|
110
|
+
return out
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def serialize_totals(model_admin, request, obj) -> dict:
|
|
114
|
+
"""The header totals named by ``api_totals`` (field names, admin methods or model attributes)."""
|
|
115
|
+
getter = getattr(model_admin, "get_api_totals", None)
|
|
116
|
+
names = getter(request, obj) if getter else getattr(model_admin, "api_totals", None)
|
|
117
|
+
return serialize_values(model_admin, obj, names, explicit=True) if names else {}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def serialize_object(model_admin, request, obj) -> dict:
|
|
121
|
+
names, explicit = detail_fields(model_admin, request, obj)
|
|
122
|
+
payload = {"pk": encode_value(obj.pk), "str": str(obj)}
|
|
123
|
+
payload.update(serialize_values(model_admin, obj, names, explicit))
|
|
124
|
+
inlines = serialize_inlines(model_admin, request, obj)
|
|
125
|
+
if inlines:
|
|
126
|
+
payload["inlines"] = inlines
|
|
127
|
+
return payload
|