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.
Files changed (49) hide show
  1. admin_api/__init__.py +9 -0
  2. admin_api/actions.py +115 -0
  3. admin_api/admin.py +108 -0
  4. admin_api/apps.py +9 -0
  5. admin_api/auth.py +62 -0
  6. admin_api/changelist.py +194 -0
  7. admin_api/checks.py +35 -0
  8. admin_api/contrib/__init__.py +1 -0
  9. admin_api/contrib/subadmin.py +37 -0
  10. admin_api/custom_views.py +458 -0
  11. admin_api/decorators.py +26 -0
  12. admin_api/deletion.py +54 -0
  13. admin_api/detail.py +127 -0
  14. admin_api/encoders.py +59 -0
  15. admin_api/errors.py +44 -0
  16. admin_api/jsonschema.py +216 -0
  17. admin_api/management/__init__.py +0 -0
  18. admin_api/management/commands/__init__.py +0 -0
  19. admin_api/management/commands/create_api_token.py +40 -0
  20. admin_api/management/commands/mcp_serve.py +86 -0
  21. admin_api/mcp/__init__.py +7 -0
  22. admin_api/mcp/bridge.py +71 -0
  23. admin_api/mcp/confirm.py +54 -0
  24. admin_api/mcp/handlers.py +665 -0
  25. admin_api/mcp/server.py +75 -0
  26. admin_api/mcp/sites.py +198 -0
  27. admin_api/mcp/stdio.py +53 -0
  28. admin_api/mcp/tools.py +84 -0
  29. admin_api/mcp/views.py +69 -0
  30. admin_api/middleware.py +18 -0
  31. admin_api/migrations/0001_initial.py +40 -0
  32. admin_api/migrations/__init__.py +0 -0
  33. admin_api/mixins.py +144 -0
  34. admin_api/models.py +113 -0
  35. admin_api/nested.py +122 -0
  36. admin_api/resolver.py +95 -0
  37. admin_api/scopes.py +121 -0
  38. admin_api/services.py +423 -0
  39. admin_api/sites.py +225 -0
  40. admin_api/views/__init__.py +0 -0
  41. admin_api/views/changelist.py +50 -0
  42. admin_api/views/custom.py +31 -0
  43. admin_api/views/detail.py +39 -0
  44. admin_api/views/nested.py +70 -0
  45. admin_api/views/registry.py +15 -0
  46. admin_api/writes.py +479 -0
  47. django_admin_api_mcp-0.1.0a2.dist-info/METADATA +274 -0
  48. django_admin_api_mcp-0.1.0a2.dist-info/RECORD +49 -0
  49. django_admin_api_mcp-0.1.0a2.dist-info/WHEEL +4 -0
admin_api/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """admin_api — make Django ModelAdmin API-ready through ``api_`` twins."""
2
+
3
+ from .custom_views import view
4
+ from .decorators import display
5
+ from .mixins import ApiAdminMixin
6
+ from .resolver import api_value, resolve
7
+ from .sites import AdminApiSite
8
+
9
+ __all__ = ["AdminApiSite", "ApiAdminMixin", "api_value", "display", "resolve", "view"]
admin_api/actions.py ADDED
@@ -0,0 +1,115 @@
1
+ """Run admin actions through the API.
2
+
3
+ ``POST /v1/<app>/<model>/actions/<name>/`` with ``{"pks": [...]}`` or ``{"all": true}``
4
+ (``all`` honours the changelist filters passed as query parameters).
5
+
6
+ The action runs exactly like in the admin: same ``get_actions()`` (or the ``api_actions`` /
7
+ ``get_api_actions`` twin), same permission filtering, same queryset (changelist filters +
8
+ selection), and a POST request carrying ``action``, ``_selected_action`` and ``post`` so
9
+ confirmation-style actions such as ``delete_selected`` complete.
10
+
11
+ An action that returns an ``HttpResponse`` (file export, intermediate page) cannot be
12
+ represented in JSON: its transaction is rolled back and ``400 action_not_supported`` is
13
+ returned. Give it an API twin, a method ``api_<action_name>(self, request, queryset)``
14
+ returning JSON-serializable data, to expose it.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from django.contrib.admin import helpers
20
+ from django.core.exceptions import PermissionDenied
21
+ from django.db import router, transaction
22
+ from django.http import HttpResponseBase, QueryDict
23
+
24
+ from . import scopes
25
+ from .changelist import build_changelist, get_columns, split_api_params
26
+ from .encoders import encode_value
27
+ from .errors import ApiError, NotFound, PermissionDeniedError
28
+ from .writes import InvalidJson, as_post_request
29
+
30
+
31
+ class ActionNotSupported(ApiError):
32
+ status = 400
33
+ code = "action_not_supported"
34
+
35
+
36
+ class NothingSelected(ApiError):
37
+ status = 400
38
+ code = "nothing_selected"
39
+
40
+
41
+ def action_parts(action):
42
+ """``(func, name, description)`` for Django < 6.1 tuples and >= 6.1 ``Action`` objects."""
43
+ if hasattr(action, "func"):
44
+ return action.func, action.name, action.description
45
+ return action[0], action[1], action[2]
46
+
47
+
48
+ def api_twin(model_admin, name):
49
+ twin = getattr(model_admin, f"api_{name}", None)
50
+ return twin if callable(twin) else None
51
+
52
+
53
+ def describe_actions(model_admin, request) -> list[dict]:
54
+ out = []
55
+ for action in model_admin.get_actions(request).values():
56
+ _func, name, description = action_parts(action)
57
+ out.append({"name": name, "description": str(description), "api_twin": api_twin(model_admin, name) is not None})
58
+ return out
59
+
60
+
61
+ def run_action(model_admin, request, name, payload: dict) -> dict:
62
+ if not isinstance(payload, dict):
63
+ raise InvalidJson("The action payload must be an object.")
64
+ actions = model_admin.get_actions(request)
65
+ if name not in actions:
66
+ raise NotFound(f"No action {name!r} (or no permission).")
67
+ func, name, _description = action_parts(actions[name])
68
+ for perm in getattr(func, "allowed_permissions", ()):
69
+ if perm in scopes.OPS: # custom permissions are left to has_<perm>_permission
70
+ scopes.check(request, model_admin.opts, perm)
71
+
72
+ select_all = bool(payload.get("all"))
73
+ pks = payload.get("pks") or []
74
+ if not select_all and (not isinstance(pks, list) or not pks):
75
+ raise NothingSelected('Send {"pks": [...]} or {"all": true}.')
76
+
77
+ split_api_params(request)
78
+ cl = build_changelist(model_admin, request, get_columns(model_admin, request))
79
+ queryset = cl.get_queryset(request)
80
+ if not select_all:
81
+ queryset = queryset.filter(pk__in=pks)
82
+ count = queryset.count()
83
+ if not count:
84
+ raise NothingSelected("No objects match the selection.")
85
+
86
+ data = QueryDict(mutable=True)
87
+ data["action"] = name
88
+ data["post"] = "yes"
89
+ data["index"] = "0"
90
+ if select_all:
91
+ data["select_across"] = "1"
92
+ else:
93
+ data.setlist(helpers.ACTION_CHECKBOX_NAME, [str(pk) for pk in pks])
94
+ data._mutable = False
95
+ post_request = as_post_request(request, data)
96
+
97
+ twin = api_twin(model_admin, name)
98
+ try:
99
+ with transaction.atomic(using=router.db_for_write(model_admin.model)):
100
+ result = twin(post_request, queryset) if twin else func(model_admin, post_request, queryset)
101
+ if isinstance(result, HttpResponseBase):
102
+ transaction.set_rollback(True)
103
+ except PermissionDenied as exc:
104
+ raise PermissionDeniedError(str(exc) or None) from exc
105
+ if isinstance(result, HttpResponseBase):
106
+ raise ActionNotSupported(
107
+ f"Action {name!r} returned a page/file (e.g. a confirmation or export); nothing was changed. "
108
+ f"Define api_{name}(self, request, queryset) on the admin to expose it in the API."
109
+ )
110
+ return {
111
+ "action": name,
112
+ "count": count,
113
+ "messages": post_request._messages.captured(),
114
+ "result": encode_value(result),
115
+ }
admin_api/admin.py ADDED
@@ -0,0 +1,108 @@
1
+ """Admin for API tokens. Registered on the wrapped site by ``AdminApiSite`` (not autodiscovered)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from django import forms
6
+ from django.contrib import admin, messages
7
+ from django.utils.translation import gettext_lazy as _
8
+
9
+ from .scopes import normalize_scopes
10
+
11
+
12
+ class ApiTokenForm(forms.ModelForm):
13
+ scopes_text = forms.CharField(
14
+ label=_("scopes"),
15
+ required=False,
16
+ widget=forms.Textarea(attrs={"rows": 4, "placeholder": "store.sales:view\nstore.*:view\ncash.*:*"}),
17
+ help_text=_(
18
+ "One per line: <app_label>.<model_name>:<view|add|change|delete>, '*' allowed in any part. "
19
+ "Scopes only narrow the user's permissions. Leave empty for the user's full permissions."
20
+ ),
21
+ )
22
+
23
+ def __init__(self, *args, **kwargs):
24
+ super().__init__(*args, **kwargs)
25
+ if self.instance and self.instance.pk:
26
+ self.fields["scopes_text"].initial = "\n".join(self.instance.scopes or [])
27
+
28
+ def clean_scopes_text(self):
29
+ return normalize_scopes(self.cleaned_data.get("scopes_text") or "")
30
+
31
+ def save(self, commit=True):
32
+ self.instance.scopes = self.cleaned_data.get("scopes_text") or []
33
+ return super().save(commit)
34
+
35
+
36
+ class ApiTokenAdmin(admin.ModelAdmin):
37
+ api_enabled = False # never expose tokens through the API itself
38
+
39
+ list_display = [
40
+ "name",
41
+ "user",
42
+ "token_prefix",
43
+ "kind",
44
+ "scope_summary",
45
+ "created",
46
+ "expires_at",
47
+ "last_used_at",
48
+ "status",
49
+ ]
50
+ list_filter = ["kind"]
51
+ search_fields = ["name", "prefix", "user__username"]
52
+ actions = ["revoke_tokens"]
53
+ form = ApiTokenForm
54
+
55
+ @admin.display(description=_("token"))
56
+ def token_prefix(self, obj):
57
+ return f"aapi_{obj.prefix}_…"
58
+
59
+ @admin.display(description=_("scopes"))
60
+ def scope_summary(self, obj):
61
+ return ", ".join(obj.scopes) if obj.scopes else _("full user permissions")
62
+
63
+ @admin.display(description=_("status"))
64
+ def status(self, obj):
65
+ if obj.revoked_at:
66
+ return _("revoked")
67
+ if obj.is_expired:
68
+ return _("expired")
69
+ return _("active")
70
+
71
+ def get_queryset(self, request):
72
+ qs = super().get_queryset(request).select_related("user")
73
+ return qs if request.user.is_superuser else qs.filter(user=request.user)
74
+
75
+ def get_fields(self, request, obj=None):
76
+ fields = ["name", "kind", "expires_at", "scopes_text"]
77
+ if request.user.is_superuser:
78
+ fields.insert(0, "user")
79
+ if obj is not None:
80
+ fields += ["token_prefix", "created", "last_used_at", "revoked_at"]
81
+ return fields
82
+
83
+ def get_readonly_fields(self, request, obj=None):
84
+ if obj is None:
85
+ return []
86
+ return ["user", "kind", "token_prefix", "created", "last_used_at", "revoked_at"]
87
+
88
+ def save_model(self, request, obj, form, change):
89
+ if not change:
90
+ if not request.user.is_superuser or not obj.user_id:
91
+ obj.user = request.user
92
+ raw = obj.set_new_secret()
93
+ super().save_model(request, obj, form, change)
94
+ self.message_user(
95
+ request,
96
+ _("Token created. Copy it now, it will not be shown again: %(raw)s") % {"raw": raw},
97
+ messages.WARNING,
98
+ )
99
+ return
100
+ super().save_model(request, obj, form, change)
101
+
102
+ @admin.action(description=_("Revoke selected tokens"), permissions=["change"])
103
+ def revoke_tokens(self, request, queryset):
104
+ count = 0
105
+ for token in queryset.filter(revoked_at__isnull=True):
106
+ token.revoke()
107
+ count += 1
108
+ self.message_user(request, _("%(count)d token(s) revoked.") % {"count": count})
admin_api/apps.py ADDED
@@ -0,0 +1,9 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class AdminApiConfig(AppConfig):
5
+ name = "admin_api"
6
+ verbose_name = "Admin API"
7
+
8
+ def ready(self):
9
+ from . import checks # noqa: F401 (registers system checks)
admin_api/auth.py ADDED
@@ -0,0 +1,62 @@
1
+ """Pluggable authenticators. Each returns a user or ``None`` (= not mine, try the next one)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from django.middleware.csrf import CsrfViewMiddleware
6
+
7
+ from .errors import NotAuthenticated, PermissionDeniedError
8
+
9
+ SAFE_METHODS = ("GET", "HEAD", "OPTIONS")
10
+
11
+
12
+ class BaseAuthenticator:
13
+ def authenticate(self, request): # pragma: no cover - interface
14
+ raise NotImplementedError
15
+
16
+
17
+ class _CsrfCheck(CsrfViewMiddleware):
18
+ def _reject(self, request, reason):
19
+ return reason
20
+
21
+
22
+ class SessionAuthenticator(BaseAuthenticator):
23
+ """Uses the Django session (same login as the admin). Enforces CSRF on unsafe methods."""
24
+
25
+ def authenticate(self, request):
26
+ user = getattr(request, "user", None)
27
+ if user is None or not user.is_authenticated:
28
+ return None
29
+ if request.method not in SAFE_METHODS:
30
+ reason = _CsrfCheck(lambda r: None).process_view(request, None, (), {})
31
+ if reason:
32
+ raise PermissionDeniedError(f"CSRF failed: {reason}", code="csrf_failed")
33
+ return user
34
+
35
+
36
+ def get_token_model():
37
+ from django.apps import apps
38
+ from django.conf import settings
39
+
40
+ return apps.get_model(getattr(settings, "ADMIN_API_TOKEN_MODEL", "admin_api.ApiToken"), require_ready=True)
41
+
42
+
43
+ class TokenAuthenticator(BaseAuthenticator):
44
+ """``Authorization: Bearer aapi_<prefix>_<secret>``. No CSRF (not cookie based).
45
+
46
+ A request that sends a Bearer token is never authenticated by the session: an invalid,
47
+ revoked or expired token is a 401, not a fall-through.
48
+ """
49
+
50
+ keyword = "bearer"
51
+
52
+ def authenticate(self, request):
53
+ header = request.META.get("HTTP_AUTHORIZATION", "")
54
+ scheme, _, raw = header.partition(" ")
55
+ if scheme.lower() != self.keyword:
56
+ return None
57
+ token = get_token_model().objects.get_for_raw(raw.strip())
58
+ if token is None or not token.user.is_active:
59
+ raise NotAuthenticated("Invalid, revoked or expired token.", code="invalid_token")
60
+ token.touch()
61
+ request.api_token = token
62
+ return token.user
@@ -0,0 +1,194 @@
1
+ """The API changelist: Django's ``ChangeList`` driven by the resolved ``api_`` twins."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+ from django.contrib.admin.utils import label_for_field, lookup_field
9
+ from django.contrib.admin.views.main import ChangeList
10
+ from django.core.exceptions import FieldDoesNotExist
11
+ from django.http import QueryDict
12
+
13
+ from .decorators import is_api_display
14
+ from .encoders import encode_value, field_type
15
+ from .errors import ApiError
16
+ from .resolver import api_value, resolve
17
+
18
+ # Query parameters owned by the API. Removed from request.GET before ChangeList sees it,
19
+ # because ChangeList treats every unknown key as a field lookup. Admin's own params
20
+ # (o, q, p, all, _facets, _to_field, ...) are left alone.
21
+ SHAPE_PARAM = "_shape"
22
+ PER_PAGE_PARAM = "_per_page"
23
+ API_PARAMS = frozenset({SHAPE_PARAM, PER_PAGE_PARAM})
24
+ SHAPES = ("objects", "columnar")
25
+
26
+
27
+ class BadLookup(ApiError):
28
+ status = 400
29
+ code = "bad_lookup"
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Column:
34
+ name: Any # list_display entry (str or callable)
35
+ key: str # key in the JSON row
36
+ kind: str # "str" | "field" | "callable"
37
+ field: Any = None
38
+
39
+ def label(self, model_admin) -> str:
40
+ if self.kind == "str":
41
+ return str(model_admin.model._meta.verbose_name)
42
+ return str(label_for_field(self.name, model_admin.model, model_admin))
43
+
44
+ def value(self, obj, model_admin):
45
+ if self.kind == "str":
46
+ return str(obj)
47
+ _f, _attr, value = lookup_field(self.name, obj, model_admin)
48
+ return encode_value(value)
49
+
50
+
51
+ def _list_display_is_explicit(model_admin) -> bool:
52
+ """True when list_display comes from an api_ twin (``get_api_list_display`` / ``api_list_display``)."""
53
+ return (
54
+ getattr(model_admin, "get_api_list_display", None) is not None
55
+ or getattr(model_admin, "api_list_display", None) is not None
56
+ )
57
+
58
+
59
+ def _model_field(model, name):
60
+ if not isinstance(name, str):
61
+ return None
62
+ try:
63
+ return model._meta.get_field(name)
64
+ except FieldDoesNotExist:
65
+ return None
66
+
67
+
68
+ def get_columns(model_admin, request) -> list[Column]:
69
+ """Resolve list_display for the API.
70
+
71
+ Model fields and ``__str__`` are always included. Anything else (admin methods, model
72
+ methods/properties, plain callables) is a *callable* and is only included when the list
73
+ comes from an api_ twin, or when it is decorated with ``@admin_api.display``.
74
+ """
75
+ explicit = _list_display_is_explicit(model_admin)
76
+ model = model_admin.model
77
+ columns = []
78
+ for name in api_value(model_admin, "list_display", request):
79
+ if name == "action_checkbox":
80
+ continue
81
+ if name == "__str__":
82
+ columns.append(Column(name, "str", "str"))
83
+ continue
84
+ field = _model_field(model, name)
85
+ if field is not None:
86
+ columns.append(Column(name, name, "field", field))
87
+ continue
88
+ if isinstance(name, str) and "__" in name and not hasattr(model_admin, name) and not hasattr(model, name):
89
+ # related lookup ("client__name"), supported by Django >= 5.1
90
+ columns.append(Column(name, name, "field"))
91
+ continue
92
+ func = name if callable(name) else getattr(model_admin, name, None) or getattr(model, name, None)
93
+ if explicit or is_api_display(func):
94
+ key = name if isinstance(name, str) else getattr(name, "__name__", repr(name))
95
+ columns.append(Column(name, key, "callable"))
96
+ return columns
97
+
98
+
99
+ class ApiChangeList(ChangeList):
100
+ """ChangeList that can skip fetching results (used by the schema endpoint)."""
101
+
102
+ def __init__(self, *args, schema_only=False, **kwargs):
103
+ self._schema_only = schema_only
104
+ super().__init__(*args, **kwargs)
105
+
106
+ def get_results(self, request):
107
+ if self._schema_only:
108
+ self.result_count = self.full_result_count = None
109
+ self.result_list = []
110
+ self.can_show_all = self.multi_page = False
111
+ self.paginator = None
112
+ self.show_full_result_count = False
113
+ self.show_admin_actions = False
114
+ return
115
+ super().get_results(request)
116
+
117
+
118
+ def split_api_params(request) -> dict:
119
+ """Move API-owned params out of request.GET. Returns them; keeps the original as ``request.api_query``."""
120
+ original = request.GET
121
+ api = {k: original.get(k) for k in API_PARAMS if k in original}
122
+ cleaned = original.copy()
123
+ for k in API_PARAMS:
124
+ cleaned.pop(k, None)
125
+ cleaned._mutable = False
126
+ request.api_query = original
127
+ request.GET = cleaned
128
+ return api
129
+
130
+
131
+ def build_changelist(model_admin, request, columns, *, per_page=None, schema_only=False) -> ApiChangeList:
132
+ from django.contrib.admin.options import IncorrectLookupParameters
133
+ from django.core.exceptions import SuspiciousOperation
134
+
135
+ if per_page is None:
136
+ per_page = resolve(model_admin, "list_per_page", request)
137
+ try:
138
+ return ApiChangeList(
139
+ request,
140
+ model_admin.model,
141
+ [c.name for c in columns],
142
+ (),
143
+ model_admin.get_list_filter(request),
144
+ model_admin.date_hierarchy,
145
+ model_admin.get_search_fields(request),
146
+ model_admin.get_list_select_related(request),
147
+ per_page,
148
+ model_admin.list_max_show_all,
149
+ (),
150
+ model_admin,
151
+ model_admin.get_sortable_by(request),
152
+ model_admin.search_help_text,
153
+ schema_only=schema_only,
154
+ )
155
+ except (IncorrectLookupParameters, SuspiciousOperation) as exc:
156
+ raise BadLookup(str(exc) or "Invalid filter, ordering or page parameter.") from exc
157
+
158
+
159
+ def describe_filters(cl: ApiChangeList) -> list[dict]:
160
+ out = []
161
+ for spec in cl.filter_specs:
162
+ expected = list(spec.expected_parameters())
163
+ choices = []
164
+ for choice in spec.choices(cl):
165
+ qs = QueryDict(choice.get("query_string", "").lstrip("?"))
166
+ choices.append(
167
+ {
168
+ "display": str(choice.get("display")),
169
+ "selected": bool(choice.get("selected")),
170
+ "params": {k: qs.get(k) for k in expected if k in qs},
171
+ }
172
+ )
173
+ out.append({"title": str(spec.title), "parameters": expected, "choices": choices})
174
+ return out
175
+
176
+
177
+ def describe_columns(columns, model_admin, request) -> list[dict]:
178
+ sortable = set(model_admin.get_sortable_by(request) or ())
179
+ out = []
180
+ for index, col in enumerate(columns):
181
+ entry = {"name": col.key, "label": col.label(model_admin), "kind": col.kind, "type": None}
182
+ if col.field is not None:
183
+ entry["type"] = field_type(col.field)
184
+ if getattr(col.field, "choices", None):
185
+ entry["choices"] = [{"value": encode_value(v), "display": str(d)} for v, d in col.field.flatchoices]
186
+ entry["sortable"] = col.name in sortable and (col.kind == "field" or _has_ordering(col, model_admin))
187
+ entry["order_index"] = index # value to use in ?o=
188
+ out.append(entry)
189
+ return out
190
+
191
+
192
+ def _has_ordering(col, model_admin) -> bool:
193
+ func = col.name if callable(col.name) else getattr(model_admin, col.name, None)
194
+ return bool(getattr(func, "admin_order_field", None))
admin_api/checks.py ADDED
@@ -0,0 +1,35 @@
1
+ from django.conf import settings
2
+ from django.core import checks
3
+
4
+ MIDDLEWARE_PATH = "admin_api.middleware.ApiRequestMiddleware"
5
+
6
+
7
+ @checks.register()
8
+ def check_middleware(app_configs=None, **kwargs):
9
+ if MIDDLEWARE_PATH not in getattr(settings, "MIDDLEWARE", []):
10
+ return [
11
+ checks.Error(
12
+ f"'{MIDDLEWARE_PATH}' must be in MIDDLEWARE.",
13
+ hint="It sets request.is_api = False on every request so admin code can branch on it.",
14
+ id="admin_api.E001",
15
+ )
16
+ ]
17
+ return []
18
+
19
+
20
+ @checks.register(checks.Tags.urls)
21
+ def check_mcp_view_tools(app_configs=None, **kwargs):
22
+ """Names of the views published as MCP tools (``mcp_tool=``) must be unique per MCP site."""
23
+ from django.core.exceptions import ImproperlyConfigured
24
+ from django.urls import get_resolver
25
+
26
+ get_resolver().url_patterns # noqa: B018 (import the URLconf, which creates the sites)
27
+ from .mcp.sites import all_mcp_sites
28
+
29
+ errors = []
30
+ for site in all_mcp_sites():
31
+ try:
32
+ site.get_tools()
33
+ except ImproperlyConfigured as exc:
34
+ errors.append(checks.Error(str(exc), obj=site, id="admin_api.E002"))
35
+ return errors
@@ -0,0 +1 @@
1
+ """Optional integrations with third-party admin libraries."""
@@ -0,0 +1,37 @@
1
+ """django-subadmin support (https://github.com/inueni/django-subadmin).
2
+
3
+ A ``SubAdmin`` is not registered on the admin site: it hangs off a registered
4
+ ``RootSubAdmin`` (``subadmins = [...]``), at any depth, and every one of its views needs
5
+ ``request.subadmin`` (a ``SubAdminHelper`` that loads and checks the ancestors). This adapter
6
+ discovers the subadmins and builds that helper before admin_api calls a nested admin.
7
+
8
+ Duck-typed: nothing here imports ``subadmin``, so admin_api does not depend on it.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from django.core.exceptions import PermissionDenied
14
+ from django.http import Http404
15
+
16
+ from ..errors import NotFound, PermissionDeniedError
17
+ from ..nested import NestedAdapter
18
+
19
+
20
+ class SubAdminAdapter(NestedAdapter):
21
+ def get_children(self, model_admin) -> list:
22
+ children = getattr(model_admin, "subadmin_instances", None) or []
23
+ return [child for child in children if self.is_child(child)]
24
+
25
+ def is_child(self, model_admin) -> bool:
26
+ return hasattr(model_admin, "get_subadmin_helper") and hasattr(model_admin, "parent_admin")
27
+
28
+ def init_args(self, child) -> tuple:
29
+ return (child.parent_model, child.parent_admin)
30
+
31
+ def prepare_request(self, model_admin, request, parents: list) -> None:
32
+ try:
33
+ request.subadmin = model_admin.get_subadmin_helper(request, [str(pk) for pk in parents])
34
+ except Http404 as exc:
35
+ raise NotFound(f"Parent objects {list(parents)!r} not found (or not related to each other).") from exc
36
+ except PermissionDenied as exc:
37
+ raise PermissionDeniedError("No permission on a parent object.") from exc