devadmin 0.1.0__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.
- devadmin/__init__.py +19 -0
- devadmin/__main__.py +5 -0
- devadmin/adapters/__init__.py +0 -0
- devadmin/adapters/base.py +175 -0
- devadmin/adapters/tortoise/__init__.py +81 -0
- devadmin/adapters/tortoise/introspect.py +209 -0
- devadmin/adapters/tortoise/models.py +34 -0
- devadmin/adapters/tortoise/queries.py +330 -0
- devadmin/adapters/tortoise/related.py +215 -0
- devadmin/adapters/tortoise/store.py +156 -0
- devadmin/auth/__init__.py +16 -0
- devadmin/auth/csrf.py +18 -0
- devadmin/auth/ip.py +28 -0
- devadmin/auth/login.py +149 -0
- devadmin/auth/session.py +94 -0
- devadmin/cli.py +314 -0
- devadmin/config.py +34 -0
- devadmin/core/__init__.py +0 -0
- devadmin/core/binding.py +609 -0
- devadmin/core/forms.py +475 -0
- devadmin/core/listing.py +400 -0
- devadmin/core/options.py +99 -0
- devadmin/core/paths.py +39 -0
- devadmin/core/site.py +288 -0
- devadmin/core/values.py +122 -0
- devadmin/history/__init__.py +38 -0
- devadmin/history/diff.py +109 -0
- devadmin/history/encoding.py +120 -0
- devadmin/history/records.py +40 -0
- devadmin/history/render.py +129 -0
- devadmin/history/service.py +256 -0
- devadmin/web/__init__.py +0 -0
- devadmin/web/app.py +106 -0
- devadmin/web/deps.py +275 -0
- devadmin/web/guard.py +178 -0
- devadmin/web/static/autocomplete.js +231 -0
- devadmin/web/static/devadmin.css +1645 -0
- devadmin/web/static/devadmin.js +129 -0
- devadmin/web/static/htmx.min.js +1 -0
- devadmin/web/static/icons/check.svg +1 -0
- devadmin/web/static/icons/clock.svg +1 -0
- devadmin/web/static/icons/cross.svg +1 -0
- devadmin/web/static/icons/down.svg +1 -0
- devadmin/web/static/icons/eye.svg +1 -0
- devadmin/web/static/icons/lock.svg +1 -0
- devadmin/web/static/icons/pencil.svg +1 -0
- devadmin/web/static/icons/plus.svg +1 -0
- devadmin/web/static/icons/right.svg +1 -0
- devadmin/web/static/icons/trash.svg +1 -0
- devadmin/web/static/icons/up.svg +1 -0
- devadmin/web/templates/_field.html +35 -0
- devadmin/web/templates/_history.html +19 -0
- devadmin/web/templates/_pagination.html +8 -0
- devadmin/web/templates/action_confirm.html +26 -0
- devadmin/web/templates/base.html +63 -0
- devadmin/web/templates/delete.html +62 -0
- devadmin/web/templates/error.html +9 -0
- devadmin/web/templates/form.html +34 -0
- devadmin/web/templates/history.html +59 -0
- devadmin/web/templates/index.html +49 -0
- devadmin/web/templates/list.html +88 -0
- devadmin/web/templates/login.html +15 -0
- devadmin/web/templates/recent.html +25 -0
- devadmin/web/views_auth.py +146 -0
- devadmin/web/views_delete.py +774 -0
- devadmin/web/views_form.py +551 -0
- devadmin/web/views_history.py +261 -0
- devadmin/web/views_list.py +246 -0
- devadmin-0.1.0.dist-info/METADATA +702 -0
- devadmin-0.1.0.dist-info/RECORD +73 -0
- devadmin-0.1.0.dist-info/WHEEL +4 -0
- devadmin-0.1.0.dist-info/entry_points.txt +3 -0
- devadmin-0.1.0.dist-info/licenses/LICENSE +21 -0
devadmin/core/binding.py
ADDED
|
@@ -0,0 +1,609 @@
|
|
|
1
|
+
import difflib
|
|
2
|
+
import inspect
|
|
3
|
+
import types
|
|
4
|
+
from collections.abc import Callable, Mapping
|
|
5
|
+
from dataclasses import dataclass, field as dataclass_field
|
|
6
|
+
from typing import Any, Literal
|
|
7
|
+
|
|
8
|
+
from devadmin.adapters.base import FieldInfo, FieldType, ModelInfo, Order
|
|
9
|
+
from devadmin.core.options import ActionOptions, DisplayOptions, ModelAdmin, SimpleFilter
|
|
10
|
+
from devadmin.core.paths import PathError, ResolvedPath, Schema, resolve_path
|
|
11
|
+
|
|
12
|
+
_NOT_SCALAR = frozenset({FieldType.FK, FieldType.M2M, FieldType.JSON, FieldType.TEXT, FieldType.UNSUPPORTED})
|
|
13
|
+
_UNSORTABLE = frozenset({FieldType.M2M, FieldType.JSON, FieldType.UNSUPPORTED})
|
|
14
|
+
_DEFAULT_FILTERS = frozenset({FieldType.BOOL, FieldType.ENUM})
|
|
15
|
+
_FILTERABLE = (FieldType.BOOL, FieldType.ENUM, FieldType.FK)
|
|
16
|
+
_CONTAINS_SEARCH = frozenset({FieldType.STR, FieldType.TEXT})
|
|
17
|
+
_EXACT_SEARCH = frozenset({FieldType.STR, FieldType.TEXT, FieldType.INT, FieldType.UUID, FieldType.DECIMAL})
|
|
18
|
+
_RESERVED_PARAMETERS = frozenset({"q", "p", "o"})
|
|
19
|
+
_PERMISSIONS = ("change", "delete", "view")
|
|
20
|
+
_BUILT_IN_ACTIONS = frozenset({"delete_selected"})
|
|
21
|
+
_DEFAULT_COLUMNS = 5
|
|
22
|
+
_OPTIONS = frozenset(
|
|
23
|
+
name for name, value in vars(ModelAdmin).items() if not name.startswith("_") and not callable(value)
|
|
24
|
+
)
|
|
25
|
+
_HOOKS = (
|
|
26
|
+
"has_view_permission",
|
|
27
|
+
"has_add_permission",
|
|
28
|
+
"has_change_permission",
|
|
29
|
+
"has_delete_permission",
|
|
30
|
+
"get_queryset_filters",
|
|
31
|
+
"save_model",
|
|
32
|
+
"delete_model",
|
|
33
|
+
)
|
|
34
|
+
_WRITE_PERMISSIONS = ("has_add_permission", "has_change_permission", "has_delete_permission")
|
|
35
|
+
_MISSING = object()
|
|
36
|
+
_SEARCH_MODES: dict[str, Literal["exact", "startswith", "contains"]] = {
|
|
37
|
+
"=": "exact",
|
|
38
|
+
"^": "startswith",
|
|
39
|
+
"": "contains",
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class Column:
|
|
45
|
+
name: str
|
|
46
|
+
label: str
|
|
47
|
+
kind: Literal["field", "path", "method"]
|
|
48
|
+
sortable_path: str | None
|
|
49
|
+
boolean: bool
|
|
50
|
+
field: FieldInfo | None = None
|
|
51
|
+
hops: tuple[FieldInfo, ...] = ()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class SearchEntry:
|
|
56
|
+
mode: Literal["exact", "startswith", "contains"]
|
|
57
|
+
path: str
|
|
58
|
+
field: FieldInfo
|
|
59
|
+
value_field: FieldInfo
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True)
|
|
63
|
+
class ActionSpec:
|
|
64
|
+
name: str
|
|
65
|
+
description: str
|
|
66
|
+
confirm: bool
|
|
67
|
+
permission: Literal["view", "change", "delete"]
|
|
68
|
+
transactional: bool
|
|
69
|
+
handler: Callable[..., Any]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(eq=False)
|
|
73
|
+
class BoundAdmin:
|
|
74
|
+
info: ModelInfo
|
|
75
|
+
fields: list[FieldInfo]
|
|
76
|
+
options: ModelAdmin
|
|
77
|
+
pk: FieldInfo
|
|
78
|
+
sensitive: set[str]
|
|
79
|
+
list_columns: list[Column]
|
|
80
|
+
link_columns: set[str]
|
|
81
|
+
search_fields: list[str]
|
|
82
|
+
filter_names: list[str]
|
|
83
|
+
filters: dict[str, FieldInfo | SimpleFilter]
|
|
84
|
+
ordering: list[Order]
|
|
85
|
+
list_per_page: int
|
|
86
|
+
select_related: list[str]
|
|
87
|
+
form_fields: list[str]
|
|
88
|
+
readonly_fields: set[str]
|
|
89
|
+
fieldsets: list[tuple[str | None, list[str]]] | None
|
|
90
|
+
actions: dict[str, ActionSpec]
|
|
91
|
+
read_only: bool
|
|
92
|
+
group: str
|
|
93
|
+
label: str
|
|
94
|
+
label_plural: str
|
|
95
|
+
search_entries: list[SearchEntry] = dataclass_field(default_factory=list)
|
|
96
|
+
filter_targets: dict[str, FieldInfo] = dataclass_field(default_factory=dict)
|
|
97
|
+
fieldset_collapsed: list[bool] | None = None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def list_problem(value: Any, items: str = "strings") -> str:
|
|
101
|
+
if isinstance(value, str):
|
|
102
|
+
return f"must be a list, not a string; write a single entry as [{value!r}]"
|
|
103
|
+
return f"must be a list of {items}"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def bind_admin(
|
|
107
|
+
info: ModelInfo,
|
|
108
|
+
schema: Schema,
|
|
109
|
+
sensitive: Mapping[str, set[str]],
|
|
110
|
+
options: ModelAdmin,
|
|
111
|
+
errors: list[str],
|
|
112
|
+
*,
|
|
113
|
+
read_only: bool,
|
|
114
|
+
group: str,
|
|
115
|
+
label: str,
|
|
116
|
+
label_plural: str,
|
|
117
|
+
shared: bool = False,
|
|
118
|
+
) -> BoundAdmin:
|
|
119
|
+
binder = _Binder(info, schema, sensitive, options, errors, shared)
|
|
120
|
+
binder.check_unknown_options()
|
|
121
|
+
broken_hooks = binder.check_hooks()
|
|
122
|
+
columns = binder.columns()
|
|
123
|
+
link_columns = binder.links(columns)
|
|
124
|
+
search_fields = binder.search()
|
|
125
|
+
filters = binder.filters()
|
|
126
|
+
ordering = binder.ordering()
|
|
127
|
+
list_per_page = binder.per_page()
|
|
128
|
+
select_related = binder.select_related()
|
|
129
|
+
form_fields, readonly_fields, fieldsets = binder.form()
|
|
130
|
+
bound = BoundAdmin(
|
|
131
|
+
info=info,
|
|
132
|
+
fields=list(binder.fields.values()),
|
|
133
|
+
options=options,
|
|
134
|
+
pk=binder.pk,
|
|
135
|
+
sensitive=set(binder.sensitive),
|
|
136
|
+
list_columns=columns,
|
|
137
|
+
link_columns=link_columns,
|
|
138
|
+
search_fields=search_fields,
|
|
139
|
+
filter_names=list(filters),
|
|
140
|
+
filters=filters,
|
|
141
|
+
ordering=ordering,
|
|
142
|
+
list_per_page=list_per_page,
|
|
143
|
+
select_related=select_related,
|
|
144
|
+
form_fields=form_fields,
|
|
145
|
+
readonly_fields=readonly_fields,
|
|
146
|
+
fieldsets=fieldsets,
|
|
147
|
+
actions=binder.actions(),
|
|
148
|
+
read_only=read_only,
|
|
149
|
+
group=group,
|
|
150
|
+
label=label,
|
|
151
|
+
label_plural=label_plural,
|
|
152
|
+
search_entries=binder.search_entries,
|
|
153
|
+
filter_targets=binder.filter_targets(filters),
|
|
154
|
+
fieldset_collapsed=binder.fieldset_collapsed(fieldsets),
|
|
155
|
+
)
|
|
156
|
+
if read_only:
|
|
157
|
+
for hook in _WRITE_PERMISSIONS:
|
|
158
|
+
if hook in broken_hooks:
|
|
159
|
+
continue
|
|
160
|
+
try:
|
|
161
|
+
setattr(options, hook, _deny)
|
|
162
|
+
except Exception as exc:
|
|
163
|
+
binder.error(hook, f"cannot be replaced to make the model read-only ({type(exc).__name__}: {exc})")
|
|
164
|
+
return bound
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _deny(*args: Any, **kwargs: Any) -> bool:
|
|
168
|
+
return False
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def stored_key(schema: Schema, field: FieldInfo) -> FieldInfo | None:
|
|
172
|
+
seen: set[str] = set()
|
|
173
|
+
while field.type is FieldType.FK and field.relation is not None:
|
|
174
|
+
target = schema.get(field.relation.target)
|
|
175
|
+
if target is None or field.relation.target in seen:
|
|
176
|
+
return None
|
|
177
|
+
seen.add(field.relation.target)
|
|
178
|
+
key = target.get(field.relation.target_pk)
|
|
179
|
+
field = key if key is not None else next(candidate for candidate in target.values() if candidate.pk)
|
|
180
|
+
return field
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
class _Binder:
|
|
184
|
+
def __init__(
|
|
185
|
+
self,
|
|
186
|
+
info: ModelInfo,
|
|
187
|
+
schema: Schema,
|
|
188
|
+
sensitive: Mapping[str, set[str]],
|
|
189
|
+
options: ModelAdmin,
|
|
190
|
+
errors: list[str],
|
|
191
|
+
shared: bool,
|
|
192
|
+
) -> None:
|
|
193
|
+
self.key = info.key
|
|
194
|
+
self.schema = schema
|
|
195
|
+
self.fields = schema[info.key]
|
|
196
|
+
self.pk = next(field for field in self.fields.values() if field.pk)
|
|
197
|
+
self.sensitive_by_model = sensitive
|
|
198
|
+
self.sensitive = sensitive[info.key]
|
|
199
|
+
self.options = options
|
|
200
|
+
self.owner = type(options).__name__
|
|
201
|
+
self.errors = errors
|
|
202
|
+
self.note = f"[{info.key}] " if shared else ""
|
|
203
|
+
self.written_columns: list[str] = []
|
|
204
|
+
self.search_entries: list[SearchEntry] = []
|
|
205
|
+
|
|
206
|
+
def error(self, option: str, message: str) -> None:
|
|
207
|
+
self.errors.append(f"{self.owner}.{option}: {self.note}{message}")
|
|
208
|
+
|
|
209
|
+
def names(self, option: str) -> list[str] | None:
|
|
210
|
+
value = getattr(self.options, option)
|
|
211
|
+
if value is None:
|
|
212
|
+
return None
|
|
213
|
+
if isinstance(value, (list, tuple)) and all(isinstance(item, str) for item in value):
|
|
214
|
+
return list(value)
|
|
215
|
+
self.error(option, list_problem(value))
|
|
216
|
+
return None
|
|
217
|
+
|
|
218
|
+
def resolve(self, option: str, path: str, context: str = "", own_pk: bool = False) -> ResolvedPath | None:
|
|
219
|
+
try:
|
|
220
|
+
resolved = resolve_path(self.schema, self.key, path)
|
|
221
|
+
except PathError as exc:
|
|
222
|
+
self.error(option, f"{context}{exc}")
|
|
223
|
+
return None
|
|
224
|
+
exempt = own_pk and not resolved.hops and resolved.field.pk
|
|
225
|
+
if resolved.field.name in self.sensitive_by_model[resolved.model_key] and not exempt:
|
|
226
|
+
self.error(option, f"{context}{path!r} is a sensitive field")
|
|
227
|
+
return None
|
|
228
|
+
return resolved
|
|
229
|
+
|
|
230
|
+
def sortable(self, option: str, path: str, context: str = "", own_pk: bool = False) -> ResolvedPath | None:
|
|
231
|
+
resolved = self.resolve(option, path, context, own_pk)
|
|
232
|
+
if resolved is not None and resolved.field.type in _UNSORTABLE:
|
|
233
|
+
self.error(option, f"{context}{path!r} is a {resolved.field.type} field and cannot be sorted")
|
|
234
|
+
return None
|
|
235
|
+
return resolved
|
|
236
|
+
|
|
237
|
+
def check_unknown_options(self) -> None:
|
|
238
|
+
for klass in type(self.options).__mro__:
|
|
239
|
+
if klass is ModelAdmin or klass is object:
|
|
240
|
+
break
|
|
241
|
+
for name, value in vars(klass).items():
|
|
242
|
+
if name.startswith("_") or name in _OPTIONS:
|
|
243
|
+
continue
|
|
244
|
+
if callable(value) or isinstance(value, (staticmethod, classmethod, property)):
|
|
245
|
+
continue
|
|
246
|
+
close = difflib.get_close_matches(name, sorted(_OPTIONS), n=1)
|
|
247
|
+
hint = f" (did you mean {close[0]!r}?)" if close else ""
|
|
248
|
+
self.error(name, f"not a supported option{hint}; prefix helper constants with an underscore")
|
|
249
|
+
|
|
250
|
+
def check_hooks(self) -> set[str]:
|
|
251
|
+
broken = set()
|
|
252
|
+
for hook in _HOOKS:
|
|
253
|
+
value = inspect.getattr_static(self.options, hook)
|
|
254
|
+
if callable(value) or isinstance(value, (staticmethod, classmethod)):
|
|
255
|
+
continue
|
|
256
|
+
self.error(hook, f"must be a method, not a {type(value).__name__}")
|
|
257
|
+
broken.add(hook)
|
|
258
|
+
return broken
|
|
259
|
+
|
|
260
|
+
def columns(self) -> list[Column]:
|
|
261
|
+
names = self.names("list_display")
|
|
262
|
+
if names is None:
|
|
263
|
+
scalar = [
|
|
264
|
+
field
|
|
265
|
+
for field in self.fields.values()
|
|
266
|
+
if not field.pk and field.type not in _NOT_SCALAR and field.name not in self.sensitive
|
|
267
|
+
]
|
|
268
|
+
defaults = [self.pk, *scalar[:_DEFAULT_COLUMNS]]
|
|
269
|
+
self.written_columns = [field.name for field in defaults]
|
|
270
|
+
return [self.field_column(field.name, ResolvedPath(self.key, field, [])) for field in defaults]
|
|
271
|
+
self.written_columns = names
|
|
272
|
+
if not names:
|
|
273
|
+
self.error("list_display", "must name at least one column")
|
|
274
|
+
columns: list[Column] = []
|
|
275
|
+
for index, name in enumerate(names):
|
|
276
|
+
if name in names[:index]:
|
|
277
|
+
self.error("list_display", f"{name!r} is listed twice")
|
|
278
|
+
continue
|
|
279
|
+
column = self.column(name)
|
|
280
|
+
if column is not None:
|
|
281
|
+
columns.append(column)
|
|
282
|
+
return columns
|
|
283
|
+
|
|
284
|
+
def column(self, name: str) -> Column | None:
|
|
285
|
+
if name in self.fields or "__" in name:
|
|
286
|
+
resolved = self.resolve("list_display", name, own_pk=True)
|
|
287
|
+
if resolved is None:
|
|
288
|
+
return None
|
|
289
|
+
if resolved.field.type is FieldType.M2M:
|
|
290
|
+
self.error("list_display", f"{name!r} is a many-to-many field and cannot be a column")
|
|
291
|
+
return None
|
|
292
|
+
return self.field_column(name, resolved)
|
|
293
|
+
method = self.method(name)
|
|
294
|
+
if method is None:
|
|
295
|
+
return None
|
|
296
|
+
meta = getattr(method, "devadmin_display", None)
|
|
297
|
+
if not isinstance(meta, DisplayOptions):
|
|
298
|
+
meta = DisplayOptions(None, None, False)
|
|
299
|
+
sortable_path = None
|
|
300
|
+
if meta.ordering is not None:
|
|
301
|
+
if self.sortable("list_display", meta.ordering, f"{name} ordering: ") is None:
|
|
302
|
+
return None
|
|
303
|
+
sortable_path = meta.ordering
|
|
304
|
+
label = meta.label if meta.label is not None else name.replace("_", " ").capitalize()
|
|
305
|
+
return Column(name, label, "method", sortable_path, meta.boolean)
|
|
306
|
+
|
|
307
|
+
def field_column(self, name: str, resolved: ResolvedPath) -> Column:
|
|
308
|
+
field = resolved.field
|
|
309
|
+
label = " ".join([hop.label for hop in resolved.hops] + [field.label]).capitalize()
|
|
310
|
+
sortable_path = None if field.type in _UNSORTABLE else name
|
|
311
|
+
kind = "path" if resolved.hops else "field"
|
|
312
|
+
return Column(name, label, kind, sortable_path, field.type is FieldType.BOOL, field, tuple(resolved.hops))
|
|
313
|
+
|
|
314
|
+
def method(self, name: str) -> Callable[..., Any] | None:
|
|
315
|
+
static = _MISSING
|
|
316
|
+
if not name.startswith("_") and not hasattr(ModelAdmin, name):
|
|
317
|
+
static = inspect.getattr_static(self.options, name, _MISSING)
|
|
318
|
+
if static is _MISSING:
|
|
319
|
+
self.error("list_display", f"{name!r} is not a field, a path or a method of {self.owner}")
|
|
320
|
+
return None
|
|
321
|
+
if isinstance(static, property):
|
|
322
|
+
self.error("list_display", f"{name!r} is a property; a column needs a method that takes the object")
|
|
323
|
+
return None
|
|
324
|
+
if not (callable(static) or isinstance(static, (staticmethod, classmethod))):
|
|
325
|
+
self.error("list_display", f"{name!r} is not a field, a path or a method of {self.owner}")
|
|
326
|
+
return None
|
|
327
|
+
try:
|
|
328
|
+
method = getattr(self.options, name)
|
|
329
|
+
except Exception as exc:
|
|
330
|
+
self.error("list_display", f"{name!r}: reading it raised {type(exc).__name__}: {exc}")
|
|
331
|
+
return None
|
|
332
|
+
try:
|
|
333
|
+
signature = inspect.signature(method)
|
|
334
|
+
except (TypeError, ValueError):
|
|
335
|
+
return method
|
|
336
|
+
try:
|
|
337
|
+
signature.bind(None)
|
|
338
|
+
except TypeError:
|
|
339
|
+
self.error("list_display", f"{name!r} must take exactly one argument, the object: {name}{signature}")
|
|
340
|
+
return None
|
|
341
|
+
return method
|
|
342
|
+
|
|
343
|
+
def links(self, columns: list[Column]) -> set[str]:
|
|
344
|
+
names = self.names("list_display_links")
|
|
345
|
+
if names is None:
|
|
346
|
+
return {columns[0].name} if columns else set()
|
|
347
|
+
for name in names:
|
|
348
|
+
if name not in self.written_columns:
|
|
349
|
+
self.error("list_display_links", f"{name!r} is not in list_display")
|
|
350
|
+
return set(names) & {column.name for column in columns}
|
|
351
|
+
|
|
352
|
+
def search(self) -> list[str]:
|
|
353
|
+
entries = self.names("search_fields")
|
|
354
|
+
if entries is None:
|
|
355
|
+
unique = [
|
|
356
|
+
field
|
|
357
|
+
for field in self.fields.values()
|
|
358
|
+
if field.type is FieldType.STR and field.unique and not field.pk and field.name not in self.sensitive
|
|
359
|
+
]
|
|
360
|
+
self.search_entries = [self.search_entry("=", self.pk.name, self.pk)]
|
|
361
|
+
self.search_entries += [self.search_entry("^", field.name, field) for field in unique]
|
|
362
|
+
return [f"={self.pk.name}", *(f"^{field.name}" for field in unique)]
|
|
363
|
+
result = []
|
|
364
|
+
for entry in entries:
|
|
365
|
+
prefix = entry[:1] if entry[:1] in ("^", "=") else ""
|
|
366
|
+
resolved = self.resolve("search_fields", entry[len(prefix):], own_pk=prefix == "=")
|
|
367
|
+
if resolved is None:
|
|
368
|
+
continue
|
|
369
|
+
field = resolved.field
|
|
370
|
+
if prefix == "=":
|
|
371
|
+
if field.type not in _EXACT_SEARCH and not field.pk:
|
|
372
|
+
self.error("search_fields", f"{entry!r}: a {field.type} field cannot be searched")
|
|
373
|
+
continue
|
|
374
|
+
elif field.type not in _CONTAINS_SEARCH:
|
|
375
|
+
self.error(
|
|
376
|
+
"search_fields",
|
|
377
|
+
f"{entry!r}: a {field.type} field cannot be searched by text; use '=' for an exact match",
|
|
378
|
+
)
|
|
379
|
+
continue
|
|
380
|
+
result.append(entry)
|
|
381
|
+
self.search_entries.append(self.search_entry(prefix, entry[len(prefix):], field))
|
|
382
|
+
return result
|
|
383
|
+
|
|
384
|
+
def search_entry(self, prefix: str, path: str, field: FieldInfo) -> SearchEntry:
|
|
385
|
+
mode = _SEARCH_MODES[prefix]
|
|
386
|
+
value_field = self.stored_key(field) if mode == "exact" else field
|
|
387
|
+
return SearchEntry(mode, path, field, value_field or field)
|
|
388
|
+
|
|
389
|
+
def stored_key(self, field: FieldInfo) -> FieldInfo | None:
|
|
390
|
+
return stored_key(self.schema, field)
|
|
391
|
+
|
|
392
|
+
def filter_targets(self, filters: Mapping[str, FieldInfo | SimpleFilter]) -> dict[str, FieldInfo]:
|
|
393
|
+
targets = {}
|
|
394
|
+
for parameter, target in filters.items():
|
|
395
|
+
if isinstance(target, FieldInfo) and target.type is FieldType.FK:
|
|
396
|
+
key = self.stored_key(target)
|
|
397
|
+
if key is not None:
|
|
398
|
+
targets[parameter] = key
|
|
399
|
+
return targets
|
|
400
|
+
|
|
401
|
+
def filters(self) -> dict[str, FieldInfo | SimpleFilter]:
|
|
402
|
+
value = self.options.list_filter
|
|
403
|
+
if value is None:
|
|
404
|
+
return {
|
|
405
|
+
field.name: field
|
|
406
|
+
for field in self.fields.values()
|
|
407
|
+
if field.type in _DEFAULT_FILTERS
|
|
408
|
+
and field.name not in self.sensitive
|
|
409
|
+
and field.name not in _RESERVED_PARAMETERS
|
|
410
|
+
}
|
|
411
|
+
if not isinstance(value, (list, tuple)):
|
|
412
|
+
self.error("list_filter", list_problem(value, "field names or SimpleFilter subclasses"))
|
|
413
|
+
return {}
|
|
414
|
+
result: dict[str, FieldInfo | SimpleFilter] = {}
|
|
415
|
+
for entry in value:
|
|
416
|
+
named = self.filter_entry(entry)
|
|
417
|
+
if named is None:
|
|
418
|
+
continue
|
|
419
|
+
parameter, target = named
|
|
420
|
+
if parameter in _RESERVED_PARAMETERS:
|
|
421
|
+
self.error("list_filter", f"parameter {parameter!r} is reserved by the list page")
|
|
422
|
+
elif parameter in result:
|
|
423
|
+
self.error("list_filter", f"parameter {parameter!r} is used twice")
|
|
424
|
+
else:
|
|
425
|
+
result[parameter] = target
|
|
426
|
+
return result
|
|
427
|
+
|
|
428
|
+
def filter_entry(self, entry: Any) -> tuple[str, FieldInfo | SimpleFilter] | None:
|
|
429
|
+
if isinstance(entry, str):
|
|
430
|
+
field = self.fields.get(entry)
|
|
431
|
+
if "__" in entry:
|
|
432
|
+
self.error("list_filter", f"{entry!r}: paths are not supported, name a field of {self.key}")
|
|
433
|
+
elif field is None:
|
|
434
|
+
self.error("list_filter", f"{self.key} has no field {entry!r}")
|
|
435
|
+
elif entry in self.sensitive:
|
|
436
|
+
self.error("list_filter", f"{entry!r} is a sensitive field")
|
|
437
|
+
elif field.type not in _FILTERABLE:
|
|
438
|
+
allowed = ", ".join(_FILTERABLE)
|
|
439
|
+
self.error("list_filter", f"{entry!r} is a {field.type} field; only {allowed} fields can be filtered")
|
|
440
|
+
else:
|
|
441
|
+
return entry, field
|
|
442
|
+
return None
|
|
443
|
+
if isinstance(entry, type) and issubclass(entry, SimpleFilter):
|
|
444
|
+
missing = [name for name in ("title", "parameter") if not _non_empty_str(getattr(entry, name, None))]
|
|
445
|
+
missing += [name for name in ("lookups", "filters") if getattr(entry, name) is getattr(SimpleFilter, name)]
|
|
446
|
+
if missing:
|
|
447
|
+
self.error("list_filter", f"{entry.__name__} must define {', '.join(missing)}")
|
|
448
|
+
return None
|
|
449
|
+
try:
|
|
450
|
+
instance = entry()
|
|
451
|
+
except Exception as exc:
|
|
452
|
+
self.error(
|
|
453
|
+
"list_filter",
|
|
454
|
+
f"{entry.__name__}: cannot be instantiated without arguments ({type(exc).__name__}: {exc})",
|
|
455
|
+
)
|
|
456
|
+
return None
|
|
457
|
+
return instance.parameter, instance
|
|
458
|
+
self.error("list_filter", f"{entry!r} is neither a field name nor a SimpleFilter subclass")
|
|
459
|
+
return None
|
|
460
|
+
|
|
461
|
+
def ordering(self) -> list[Order]:
|
|
462
|
+
entries = self.names("ordering")
|
|
463
|
+
if not entries:
|
|
464
|
+
return [Order(self.pk.name, True)]
|
|
465
|
+
result = []
|
|
466
|
+
for entry in entries:
|
|
467
|
+
descending = entry.startswith("-")
|
|
468
|
+
path = entry[1:] if descending else entry
|
|
469
|
+
if self.sortable("ordering", path, own_pk=True) is not None:
|
|
470
|
+
result.append(Order(path, descending))
|
|
471
|
+
return result
|
|
472
|
+
|
|
473
|
+
def per_page(self) -> int:
|
|
474
|
+
value = self.options.list_per_page
|
|
475
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
|
|
476
|
+
self.error("list_per_page", "must be a positive integer")
|
|
477
|
+
return ModelAdmin.list_per_page
|
|
478
|
+
return value
|
|
479
|
+
|
|
480
|
+
def select_related(self) -> list[str]:
|
|
481
|
+
result = []
|
|
482
|
+
for path in self.names("list_select_related") or []:
|
|
483
|
+
resolved = self.resolve("list_select_related", path)
|
|
484
|
+
if resolved is None:
|
|
485
|
+
continue
|
|
486
|
+
if resolved.field.type is not FieldType.FK:
|
|
487
|
+
self.error("list_select_related", f"{path!r} is a {resolved.field.type} field, not a foreign key")
|
|
488
|
+
continue
|
|
489
|
+
result.append(path)
|
|
490
|
+
return result
|
|
491
|
+
|
|
492
|
+
def form(self) -> tuple[list[str], set[str], list[tuple[str | None, list[str]]] | None]:
|
|
493
|
+
fields = self.names("fields")
|
|
494
|
+
fieldsets = self.fieldsets()
|
|
495
|
+
if fields is not None and fieldsets is not None:
|
|
496
|
+
self.error("fields", "cannot be used together with fieldsets")
|
|
497
|
+
fieldsets = None
|
|
498
|
+
if fieldsets is not None:
|
|
499
|
+
listed = self.form_names("fieldsets", [name for _, names in fieldsets for name in names])
|
|
500
|
+
elif fields is not None:
|
|
501
|
+
listed = self.form_names("fields", fields)
|
|
502
|
+
else:
|
|
503
|
+
listed = [name for name in self.fields if name not in self.sensitive]
|
|
504
|
+
excluded = set(self.form_names("exclude", self.names("exclude") or [], allow_sensitive=True))
|
|
505
|
+
form_fields = [name for name in listed if name not in excluded]
|
|
506
|
+
readonly = set()
|
|
507
|
+
for name in self.form_names("readonly_fields", self.names("readonly_fields") or []):
|
|
508
|
+
if name in form_fields:
|
|
509
|
+
readonly.add(name)
|
|
510
|
+
else:
|
|
511
|
+
self.error("readonly_fields", f"{name!r} is not in the form")
|
|
512
|
+
if fieldsets is not None:
|
|
513
|
+
fieldsets = [(title, [name for name in names if name not in excluded]) for title, names in fieldsets]
|
|
514
|
+
return form_fields, readonly, fieldsets
|
|
515
|
+
|
|
516
|
+
def form_names(self, option: str, names: list[str], allow_sensitive: bool = False) -> list[str]:
|
|
517
|
+
result: list[str] = []
|
|
518
|
+
for name in names:
|
|
519
|
+
if name in result:
|
|
520
|
+
self.error(option, f"{name!r} is listed twice")
|
|
521
|
+
elif name not in self.fields:
|
|
522
|
+
self.error(option, f"{self.key} has no field {name!r}")
|
|
523
|
+
elif name in self.sensitive and not allow_sensitive:
|
|
524
|
+
self.error(option, f"{name!r} is a sensitive field")
|
|
525
|
+
else:
|
|
526
|
+
result.append(name)
|
|
527
|
+
return result
|
|
528
|
+
|
|
529
|
+
def fieldset_collapsed(self, fieldsets: list[tuple[str | None, list[str]]] | None) -> list[bool] | None:
|
|
530
|
+
if fieldsets is None:
|
|
531
|
+
return None
|
|
532
|
+
return [bool(spec.get("collapsed")) for _, spec in self.options.fieldsets]
|
|
533
|
+
|
|
534
|
+
def fieldsets(self) -> list[tuple[str | None, list[str]]] | None:
|
|
535
|
+
value = self.options.fieldsets
|
|
536
|
+
if value is None:
|
|
537
|
+
return None
|
|
538
|
+
if isinstance(value, (list, tuple)) and all(_is_fieldset(entry) for entry in value):
|
|
539
|
+
return [(title, list(spec["fields"])) for title, spec in value]
|
|
540
|
+
self.error("fieldsets", "must be a list of (title, {'fields': [names]}) pairs")
|
|
541
|
+
return None
|
|
542
|
+
|
|
543
|
+
def actions(self) -> dict[str, ActionSpec]:
|
|
544
|
+
value = self.options.actions
|
|
545
|
+
if value is None:
|
|
546
|
+
return {}
|
|
547
|
+
if not isinstance(value, (list, tuple)):
|
|
548
|
+
self.error("actions", list_problem(value, "method names or functions"))
|
|
549
|
+
return {}
|
|
550
|
+
result: dict[str, ActionSpec] = {}
|
|
551
|
+
for entry in value:
|
|
552
|
+
spec = self.action(entry)
|
|
553
|
+
if spec is None:
|
|
554
|
+
continue
|
|
555
|
+
if spec.name in result:
|
|
556
|
+
self.error("actions", f"{spec.name!r} is listed twice")
|
|
557
|
+
else:
|
|
558
|
+
result[spec.name] = spec
|
|
559
|
+
return result
|
|
560
|
+
|
|
561
|
+
def action(self, entry: Any) -> ActionSpec | None:
|
|
562
|
+
if isinstance(entry, str):
|
|
563
|
+
name, function = entry, getattr(type(self.options), entry, None) if entry.isidentifier() else None
|
|
564
|
+
if not callable(function):
|
|
565
|
+
self.error("actions", f"{entry!r} is not a method of {self.owner}")
|
|
566
|
+
return None
|
|
567
|
+
elif callable(entry):
|
|
568
|
+
name, function = getattr(entry, "__name__", None), entry
|
|
569
|
+
if not isinstance(name, str) or not name.isidentifier():
|
|
570
|
+
self.error("actions", f"{entry!r}: an action must be a named function, not a lambda")
|
|
571
|
+
return None
|
|
572
|
+
else:
|
|
573
|
+
self.error("actions", f"{entry!r} is neither a method name nor a function")
|
|
574
|
+
return None
|
|
575
|
+
meta = getattr(function, "devadmin_action", None)
|
|
576
|
+
if not isinstance(meta, ActionOptions):
|
|
577
|
+
self.error("actions", f"{name!r} is not decorated with @action")
|
|
578
|
+
return None
|
|
579
|
+
if name in _BUILT_IN_ACTIONS:
|
|
580
|
+
self.error("actions", f"{name!r} is the name of a built-in action")
|
|
581
|
+
return None
|
|
582
|
+
if meta.permission not in _PERMISSIONS:
|
|
583
|
+
self.error("actions", f"{name!r}: permission must be one of {', '.join(_PERMISSIONS)}")
|
|
584
|
+
return None
|
|
585
|
+
if not _non_empty_str(meta.description):
|
|
586
|
+
self.error("actions", f"{name!r}: description must be a non-empty string")
|
|
587
|
+
return None
|
|
588
|
+
if getattr(type(self.options), name, None) is function:
|
|
589
|
+
handler = getattr(self.options, name)
|
|
590
|
+
else:
|
|
591
|
+
handler = types.MethodType(function, self.options)
|
|
592
|
+
transactional = bool(meta.transactional or self.options.transactional)
|
|
593
|
+
return ActionSpec(name, meta.description, meta.confirm, meta.permission, transactional, handler)
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def _non_empty_str(value: Any) -> bool:
|
|
597
|
+
return isinstance(value, str) and bool(value)
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
def _is_fieldset(entry: Any) -> bool:
|
|
601
|
+
if not isinstance(entry, (list, tuple)) or len(entry) != 2:
|
|
602
|
+
return False
|
|
603
|
+
title, spec = entry
|
|
604
|
+
if title is not None and not isinstance(title, str):
|
|
605
|
+
return False
|
|
606
|
+
if not isinstance(spec, dict):
|
|
607
|
+
return False
|
|
608
|
+
names = spec.get("fields")
|
|
609
|
+
return isinstance(names, (list, tuple)) and all(isinstance(name, str) for name in names)
|