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.
Files changed (73) hide show
  1. devadmin/__init__.py +19 -0
  2. devadmin/__main__.py +5 -0
  3. devadmin/adapters/__init__.py +0 -0
  4. devadmin/adapters/base.py +175 -0
  5. devadmin/adapters/tortoise/__init__.py +81 -0
  6. devadmin/adapters/tortoise/introspect.py +209 -0
  7. devadmin/adapters/tortoise/models.py +34 -0
  8. devadmin/adapters/tortoise/queries.py +330 -0
  9. devadmin/adapters/tortoise/related.py +215 -0
  10. devadmin/adapters/tortoise/store.py +156 -0
  11. devadmin/auth/__init__.py +16 -0
  12. devadmin/auth/csrf.py +18 -0
  13. devadmin/auth/ip.py +28 -0
  14. devadmin/auth/login.py +149 -0
  15. devadmin/auth/session.py +94 -0
  16. devadmin/cli.py +314 -0
  17. devadmin/config.py +34 -0
  18. devadmin/core/__init__.py +0 -0
  19. devadmin/core/binding.py +609 -0
  20. devadmin/core/forms.py +475 -0
  21. devadmin/core/listing.py +400 -0
  22. devadmin/core/options.py +99 -0
  23. devadmin/core/paths.py +39 -0
  24. devadmin/core/site.py +288 -0
  25. devadmin/core/values.py +122 -0
  26. devadmin/history/__init__.py +38 -0
  27. devadmin/history/diff.py +109 -0
  28. devadmin/history/encoding.py +120 -0
  29. devadmin/history/records.py +40 -0
  30. devadmin/history/render.py +129 -0
  31. devadmin/history/service.py +256 -0
  32. devadmin/web/__init__.py +0 -0
  33. devadmin/web/app.py +106 -0
  34. devadmin/web/deps.py +275 -0
  35. devadmin/web/guard.py +178 -0
  36. devadmin/web/static/autocomplete.js +231 -0
  37. devadmin/web/static/devadmin.css +1645 -0
  38. devadmin/web/static/devadmin.js +129 -0
  39. devadmin/web/static/htmx.min.js +1 -0
  40. devadmin/web/static/icons/check.svg +1 -0
  41. devadmin/web/static/icons/clock.svg +1 -0
  42. devadmin/web/static/icons/cross.svg +1 -0
  43. devadmin/web/static/icons/down.svg +1 -0
  44. devadmin/web/static/icons/eye.svg +1 -0
  45. devadmin/web/static/icons/lock.svg +1 -0
  46. devadmin/web/static/icons/pencil.svg +1 -0
  47. devadmin/web/static/icons/plus.svg +1 -0
  48. devadmin/web/static/icons/right.svg +1 -0
  49. devadmin/web/static/icons/trash.svg +1 -0
  50. devadmin/web/static/icons/up.svg +1 -0
  51. devadmin/web/templates/_field.html +35 -0
  52. devadmin/web/templates/_history.html +19 -0
  53. devadmin/web/templates/_pagination.html +8 -0
  54. devadmin/web/templates/action_confirm.html +26 -0
  55. devadmin/web/templates/base.html +63 -0
  56. devadmin/web/templates/delete.html +62 -0
  57. devadmin/web/templates/error.html +9 -0
  58. devadmin/web/templates/form.html +34 -0
  59. devadmin/web/templates/history.html +59 -0
  60. devadmin/web/templates/index.html +49 -0
  61. devadmin/web/templates/list.html +88 -0
  62. devadmin/web/templates/login.html +15 -0
  63. devadmin/web/templates/recent.html +25 -0
  64. devadmin/web/views_auth.py +146 -0
  65. devadmin/web/views_delete.py +774 -0
  66. devadmin/web/views_form.py +551 -0
  67. devadmin/web/views_history.py +261 -0
  68. devadmin/web/views_list.py +246 -0
  69. devadmin-0.1.0.dist-info/METADATA +702 -0
  70. devadmin-0.1.0.dist-info/RECORD +73 -0
  71. devadmin-0.1.0.dist-info/WHEEL +4 -0
  72. devadmin-0.1.0.dist-info/entry_points.txt +3 -0
  73. devadmin-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,702 @@
1
+ Metadata-Version: 2.4
2
+ Name: devadmin
3
+ Version: 0.1.0
4
+ Summary: A reusable developer admin panel for FastAPI projects
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Keywords: fastapi,admin,tortoise-orm,audit-log,history
8
+ Author: Ulugbek Narzillayev
9
+ Requires-Python: >=3.12
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Framework :: FastAPI
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Topic :: Internet :: WWW/HTTP
16
+ Provides-Extra: tortoise
17
+ Requires-Dist: fastapi (>=0.110)
18
+ Requires-Dist: itsdangerous (>=2.1)
19
+ Requires-Dist: jinja2 (>=3.1)
20
+ Requires-Dist: python-multipart (>=0.0.9)
21
+ Requires-Dist: tortoise-orm (>=0.25,<0.26) ; extra == "tortoise"
22
+ Project-URL: Issues, https://github.com/unarzillayev/devadmin/issues
23
+ Project-URL: Repository, https://github.com/unarzillayev/devadmin
24
+ Description-Content-Type: text/markdown
25
+
26
+ # devadmin
27
+
28
+ devadmin is a developer admin panel for FastAPI projects, in the spirit of Django's admin. You mount it
29
+ at a URL and every model of your project gets a list page, search, filters, forms and delete pages,
30
+ with per-model overrides in a `ModelAdmin` class. Every change made through the panel is recorded in a
31
+ per-object history that stores the old and the new values.
32
+
33
+ The core does not depend on an ORM. Version 0.1.0 ships one adapter, for Tortoise ORM.
34
+
35
+ ## Contents
36
+
37
+ - [Requirements and install](#requirements-and-install)
38
+ - [Quick start](#quick-start)
39
+ - [Configuration reference](#configuration-reference)
40
+ - [Customising a model](#customising-a-model)
41
+ - [How the panel writes](#how-the-panel-writes)
42
+ - [How the panel deletes](#how-the-panel-deletes)
43
+ - [History](#history)
44
+ - [Access and security](#access-and-security)
45
+ - [Command line](#command-line)
46
+ - [Limitations of 0.1.0](#limitations-of-010)
47
+ - [Development](#development)
48
+
49
+ ## Requirements and install
50
+
51
+ - Python 3.12 or newer.
52
+ - FastAPI, Jinja2, itsdangerous and python-multipart are installed with the package.
53
+ - Tortoise ORM 0.25.x comes with the `tortoise` extra. Install the package with that extra.
54
+
55
+ ```bash
56
+ pip install "devadmin[tortoise]"
57
+ ```
58
+
59
+ With Poetry:
60
+
61
+ ```bash
62
+ poetry add "devadmin[tortoise]"
63
+ ```
64
+
65
+ ## Quick start
66
+
67
+ The examples use a project package `myproject` with a Tortoise app labelled `models` that contains a
68
+ `User` model with the fields `email`, `password_hash`, `is_superuser` and `is_active`.
69
+
70
+ **1. Add the history models to your Tortoise app.** devadmin keeps its history in two tables, defined
71
+ as Tortoise models in `devadmin.adapters.tortoise.models`. Add that module to the same app (and so the
72
+ same connection) as your own models:
73
+
74
+ ```python
75
+ TORTOISE_ORM = {
76
+ "connections": {"default": DATABASE_URL},
77
+ "apps": {
78
+ "models": {
79
+ "models": ["myproject.models", "devadmin.adapters.tortoise.models", "aerich.models"],
80
+ "default_connection": "default",
81
+ },
82
+ },
83
+ }
84
+ ```
85
+
86
+ **2. Write the configuration** in a module of its own, so the web application and the command line can
87
+ both import it:
88
+
89
+ ```python
90
+ # myproject/admin_panel.py
91
+ from tortoise import Tortoise, connections
92
+
93
+ from devadmin import AdminConfig
94
+ from devadmin.adapters.tortoise import TortoiseAdapter
95
+ from myproject.security import verify_password
96
+ from myproject.settings import DEVADMIN_SECRET_KEY, TORTOISE_ORM
97
+
98
+
99
+ async def init_db() -> None:
100
+ await Tortoise.init(config=TORTOISE_ORM)
101
+
102
+
103
+ config = AdminConfig(
104
+ adapter=TortoiseAdapter(),
105
+ user_model="models.User",
106
+ login_field="email",
107
+ password_field="password_hash",
108
+ verify_password=verify_password,
109
+ secret_key=DEVADMIN_SECRET_KEY,
110
+ admin_modules=["myproject.admin"],
111
+ exclude_models=["models.Aerich"],
112
+ startup=init_db,
113
+ shutdown=connections.close_all,
114
+ )
115
+ ```
116
+
117
+ `verify_password(plain, hashed)` is your project's own password check. `secret_key` must be at least
118
+ 16 characters; keep it secret, it signs the panel's cookies. `exclude_models=["models.Aerich"]` keeps
119
+ aerich's bookkeeping table out of the panel; leave it out if you do not use aerich, because an unknown
120
+ model name stops the application. `startup` and `shutdown` are used only by the command line.
121
+
122
+ **3. Mount the panel:**
123
+
124
+ ```python
125
+ # myproject/main.py
126
+ from collections.abc import AsyncIterator
127
+ from contextlib import asynccontextmanager
128
+
129
+ from fastapi import FastAPI
130
+ from tortoise import connections
131
+
132
+ from devadmin import create_admin
133
+ from myproject.admin_panel import config, init_db
134
+
135
+ admin = create_admin(config)
136
+
137
+
138
+ @asynccontextmanager
139
+ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
140
+ await init_db()
141
+ await admin.state.devadmin.ready()
142
+ yield
143
+ await connections.close_all()
144
+
145
+
146
+ app = FastAPI(lifespan=lifespan)
147
+ app.mount("/dev-admin", admin)
148
+ ```
149
+
150
+ `create_admin` returns a FastAPI application. It does not read the models yet, because a host normally
151
+ starts its ORM in a lifespan handler, after import. The panel builds its registry on the first request.
152
+ `await admin.state.devadmin.ready()` builds it at startup instead, so a configuration error stops the
153
+ application before it serves anything. The panel has no environment switches of its own: it behaves the
154
+ same wherever it is mounted.
155
+
156
+ **4. Create the two history tables** with your migration tool. The package ships models, not
157
+ migrations. With aerich:
158
+
159
+ ```bash
160
+ aerich migrate --name devadmin_history
161
+ aerich upgrade
162
+ ```
163
+
164
+ **5. Grant yourself access.** Access is one boolean column on your user table (`is_superuser` by
165
+ default). Set it with the command line; see [Command line](#command-line):
166
+
167
+ ```bash
168
+ devadmin grant you@example.com --config myproject.admin_panel:config
169
+ ```
170
+
171
+ **6. Open the panel** at `https://<your host>/dev-admin/` and log in with your own email and password.
172
+
173
+ The session cookie is `Secure` by default, so the browser returns it only over HTTPS (browsers make an
174
+ exception for `localhost`). To use the panel over plain HTTP on another host, pass
175
+ `secure_cookies=False`.
176
+
177
+ ## Configuration reference
178
+
179
+ Configuration is a Python object, not environment variables: your project reads its own settings and
180
+ passes the values in.
181
+
182
+ | Field | Type | Default | Meaning |
183
+ |---|---|---|---|
184
+ | `adapter` | adapter object | required | `TortoiseAdapter()`. `TortoiseAdapter(connection_name=...)` selects a named connection. |
185
+ | `user_model` | `str` | required | Model key of your user table, `"<app label>.<ModelName>"`, for example `"models.User"`. |
186
+ | `login_field` | `str` | required | String field typed into the login form. |
187
+ | `password_field` | `str` | required | Field holding the stored password hash. |
188
+ | `verify_password` | `Callable[[str, str], bool]` | required | `verify_password(plain, hashed)`. Only a return value of `True` lets the user in. May be `async def`. |
189
+ | `secret_key` | `str` | required | At least 16 characters. Signs the session, CSRF and message cookies. |
190
+ | `access_flag` | `str` | `"is_superuser"` | Boolean field that must be true to enter the panel. |
191
+ | `title` | `str` | `"devadmin"` | Shown in the page header and the browser tab. |
192
+ | `allowed_ips` | `list[str]` | `[]` | Addresses or networks (`"10.0.0.0/8"`) allowed to reach the panel. Empty means no restriction. |
193
+ | `client_ip` | `Callable[[Request], str] \| None` | `None` | Returns the real client address of a request. Without it the panel uses the address of the direct peer. |
194
+ | `login_rate_limiter` | `Callable[[Request, str], Awaitable[bool]] \| None` | `None` | Called with the request and the typed login, stripped of surrounding whitespace and case-folded, before each login attempt. Returning `False` refuses the attempt. |
195
+ | `admin_modules` | `list[str]` | `[]` | Modules that hold your `ModelAdmin` classes. |
196
+ | `read_only_models` | `list[str]` | `[]` | Model keys that can be viewed but not added to, changed or deleted from. |
197
+ | `exclude_models` | `list[str]` | `[]` | Model keys left out of the panel. |
198
+ | `groups` | `dict[str, list[str]] \| None` | `None` | Groups of the home page and the sidebar, group name to model keys. Configured groups come first, in the order written; a model in no group goes into a group named after the Python module that defines it, and those follow alphabetically. |
199
+ | `sensitive_patterns` | `tuple[str, ...]` | `("password", "secret", "token", "hash")` | A field whose name contains one of these (case-insensitive) is sensitive. |
200
+ | `session_seconds` | `int` | `28800` | Session lifetime in seconds (8 hours). |
201
+ | `secure_cookies` | `bool` | `True` | Marks the panel's cookies `Secure`. |
202
+ | `exact_count_threshold` | `int` | `100_000` | Above this estimated row count an unfiltered list shows "about N rows" and previous/next links instead of page numbers. Estimates come from PostgreSQL only. |
203
+ | `max_cascade_rows` | `int` | `1000` | Largest number of related rows a delete may affect. |
204
+ | `startup` | `Callable[[], Awaitable[None]] \| None` | `None` | Awaited by the command line before it works, to start your ORM. The web panel ignores it. |
205
+ | `shutdown` | `Callable[[], Awaitable[None]] \| None` | `None` | Awaited by the command line afterwards. The web panel ignores it. |
206
+
207
+ The configuration is validated when the registry is built (the first request, or `ready()`), and
208
+ `allowed_ips` already in `create_admin`. A wrong value stops the application with a `ConfigError` that
209
+ lists every problem, one per line, each naming the field, for example
210
+ `AdminConfig.secret_key: must be a string of at least 16 characters` or
211
+ `AdminConfig.access_flag: models.User has no field 'is_staff'`. The checks cover the model and field
212
+ names (the login field must be a string field and the access flag a boolean field), the model lists,
213
+ `groups`, `sensitive_patterns`, `secret_key`, the three numbers, `allowed_ips`, `startup` and `shutdown`.
214
+
215
+ ## Customising a model
216
+
217
+ Every model appears in the panel with defaults. To change how one model behaves, write a `ModelAdmin`
218
+ subclass, register it with `@register("<app label>.<ModelName>")`, and list its module in
219
+ `admin_modules`. The example is for an `Order` model with `number` (unique string), `customer`
220
+ (foreign key to `User`), `status` (enum), `total` (decimal) and `paid_at` (nullable date-time). Its
221
+ action calls a host service, `order_service.cancel(order_id)`, that opens and commits its own
222
+ transaction; see [How the panel writes](#how-the-panel-writes) for what that means for history.
223
+
224
+ ```python
225
+ # myproject/admin.py
226
+ from devadmin import ModelAdmin, SimpleFilter, action, display, register
227
+ from devadmin.adapters.base import Filter
228
+ from myproject.services import orders as order_service
229
+
230
+
231
+ class PaidFilter(SimpleFilter):
232
+ title = "Payment"
233
+ parameter = "paid"
234
+
235
+ def lookups(self, request):
236
+ return [("yes", "Paid"), ("no", "Not paid")]
237
+
238
+ def filters(self, value):
239
+ return [Filter("paid_at", "isnull", value == "no")]
240
+
241
+
242
+ @register("models.Order")
243
+ class OrderAdmin(ModelAdmin):
244
+ list_display = ["id", "number", "customer__email", "status", "is_large"]
245
+ search_fields = ["=id", "^number", "customer__email"]
246
+ list_filter = ["status", PaidFilter]
247
+ list_per_page = 100
248
+ fieldsets = [
249
+ (None, {"fields": ["number", "customer", "status", "total"]}),
250
+ ("Payment", {"fields": ["paid_at"], "collapsed": True}),
251
+ ]
252
+ readonly_fields = ["status"]
253
+ actions = ["cancel"]
254
+
255
+ @display(label="Large", boolean=True, ordering="total")
256
+ def is_large(self, obj):
257
+ return obj.total >= 1000
258
+
259
+ @action(description="Cancel selected orders", confirm=True)
260
+ async def cancel(self, request, objects):
261
+ for order in objects:
262
+ await order_service.cancel(order.id)
263
+
264
+ def has_delete_permission(self, request, obj=None):
265
+ return False
266
+ ```
267
+
268
+ The panel imports the modules in `admin_modules` when it builds its registry. It applies only the
269
+ registrations made in those modules or their submodules, so a class registered elsewhere, or for
270
+ another panel, does not leak in. A submodule counts once it is imported, for example by its package's
271
+ `__init__.py`. Registering two different classes for the same model is an error.
272
+
273
+ ### Options
274
+
275
+ | Option | Default | Meaning |
276
+ |---|---|---|
277
+ | `list_display` | primary key and up to five scalar fields | Columns. Each entry is a field, a path across foreign keys (`"customer__email"`), or the name of a method on the class that takes the object. Decorate a method with `@display(label=, ordering=, boolean=)`: `ordering` is the path the column sorts by (without it the column is not sortable), `boolean=True` shows a yes/no mark. |
278
+ | `list_display_links` | the first column | Columns that link to the object's page. Each must be in `list_display`. |
279
+ | `search_fields` | `=` primary key, `^` every unique string field | Fields or paths searched by the search box. Prefix `=` for an exact match (string, text, integer, decimal and UUID fields; case-insensitive for text), `^` for starts-with, none for contains; the last two need a string or text field and ignore case. Each word of the query must match at least one field; a quoted phrase counts as one word. |
280
+ | `list_filter` | boolean and enum fields | Field names of the model itself (boolean, enum or foreign-key fields; no paths), or `SimpleFilter` subclasses. `q`, `p` and `o` are reserved parameter names. |
281
+ | `ordering` | primary key, descending | Paths, `"-"` prefix for descending. The primary key is always added last, so the order is stable. |
282
+ | `list_per_page` | `50` | Rows per page, a positive integer. |
283
+ | `list_select_related` | none | Foreign-key paths to join when loading the list. Paths used in `list_display` are joined without it. |
284
+ | `fields` | every non-sensitive field | Fields shown in the form, in this order. Cannot be combined with `fieldsets`. |
285
+ | `exclude` | none | Fields removed from the form. |
286
+ | `fieldsets` | none | `[(title or None, {"fields": [...], "collapsed": True})]`. `collapsed` is optional; a collapsed group opens when one of its fields has an error. |
287
+ | `readonly_fields` | none | Form fields shown but not editable. Each must be in the form. |
288
+ | `actions` | none | Names of methods decorated with `@action` (or such functions). Bulk "Delete selected" is built in and needs no entry. |
289
+ | `transactional` | `False` | Runs an overridden `save_model`, `delete_model` and every action of the class inside one transaction with its history. See [How the panel writes](#how-the-panel-writes). |
290
+
291
+ A `SimpleFilter` subclass sets `title` and `parameter` and implements `lookups(request)`, which returns
292
+ `(value, label)` pairs, and `filters(value)`, which returns a list of
293
+ `devadmin.adapters.base.Filter(path, op, value)`. `op` is one of `"eq"`, `"iexact"`, `"istartswith"`,
294
+ `"icontains"`, `"isnull"`, `"in"`. A value that is not one of the lookups is refused with a 400.
295
+
296
+ `@action(description=, confirm=False, permission="change", transactional=False)` declares an action.
297
+ The method is called as `action(request, objects)`, sync or async, with the selected rows that still
298
+ exist. `confirm=True` shows a confirmation page first. `permission` is `"view"`, `"change"` or
299
+ `"delete"`; the panel checks the matching `has_*_permission` for every selected row. If the method
300
+ returns a Starlette `Response`, the panel returns it; otherwise it redirects to the list with a message.
301
+
302
+ ### Hooks
303
+
304
+ | Method | Default | Meaning |
305
+ |---|---|---|
306
+ | `has_view_permission(request, obj=None)` | `True` | `False` hides the model from the sidebar and answers its pages with 404. |
307
+ | `has_add_permission(request)` | `True` | `False` removes the add page. |
308
+ | `has_change_permission(request, obj=None)` | `True` | `False` with view permission shows the form read-only. |
309
+ | `has_delete_permission(request, obj=None)` | `True` | `False` removes the delete page and "Delete selected". |
310
+ | `get_queryset_filters(request)` | `[]` | A list of `Filter` applied to the list page, to the autocomplete of foreign keys that point at this model, to the rows an action or "Delete selected" receives, and to the row the change, delete and history pages load by its key. A row outside these filters answers 404 there. |
311
+ | `save_model(request, obj, data, is_new)` | the panel saves | Replaces the panel's own save. `data` maps field names to Python values (a foreign key as the target's key). For an update, `obj` is the loaded row and `data` holds only the fields the user changed. For a create, `obj` is `None`, `data` holds the submitted fields, and the method must return the created object. |
312
+ | `delete_model(request, obj)` | the panel deletes | Replaces the panel's own delete, called once per object. |
313
+
314
+ For a model in `read_only_models` the panel replaces the add, change and delete permissions with a
315
+ refusal, whatever the class says.
316
+
317
+ ### Defaults
318
+
319
+ A model with no class gets: the primary key and up to five scalar fields as columns (foreign keys,
320
+ many-to-many, JSON, long text and sensitive fields are skipped); search by exact primary key and by the
321
+ start of each unique string field; a filter for each boolean and enum field; newest first by primary
322
+ key; 50 rows per page; a form with every non-sensitive field. Primary keys of existing rows, generated
323
+ keys, automatic timestamps, many-to-many fields and field types the adapter does not support are
324
+ read-only in the form.
325
+
326
+ The search of a model also serves the autocomplete box of every foreign key that points at it. A
327
+ model with no class is therefore found in those boxes only by its key and its unique string fields;
328
+ give the target model `search_fields` (for example `["name"]`) to find its rows by name.
329
+
330
+ A row is named by its model's `__str__`. A model without one is named by the first non-empty value
331
+ among its string fields `name`, `title`, `full_name`, `email`, `username`, `code`, `slug`, `label` and
332
+ `number`, and by `Class #pk` when it has none of them. History stores the name a row had when the
333
+ change was made, so older entries keep the old name.
334
+
335
+ The home page lists every model once, grouped, with links to add and to open it, next to the ten most
336
+ recent actions. The other pages carry the same groups in a sidebar with a filter box; `/` moves the
337
+ cursor into it.
338
+
339
+ ### Validation
340
+
341
+ Every option is checked when the registry is built. A wrong option name, an unknown field, a sensitive
342
+ field in a list, a column that cannot be sorted or a method with the wrong signature stops the
343
+ application with a `ConfigError` naming the class and the option, for example
344
+ `OrderAdmin.list_display: 'totl' is not a field, a path or a method of OrderAdmin` or
345
+ `OrderAdmin.list_filters: not a supported option (did you mean 'list_filter'?); prefix helper constants with an underscore`.
346
+ Class attributes that are not options must start with an underscore.
347
+
348
+ ## How the panel writes
349
+
350
+ Read this before you let the panel touch production data.
351
+
352
+ - An untouched Save writes nothing and records nothing. Only fields the user actually changed are
353
+ written.
354
+ - The panel's own create and update, and the history entry for it, commit in one transaction, or
355
+ neither does.
356
+ - For an ordinary model the adapter writes only the changed columns. A model with its own `save()`
357
+ method or a `pre_save` handler is saved whole, because such code may change other columns; for those
358
+ models a concurrent change to another column of the same row can be overwritten, as with any full ORM
359
+ save. For ordinary models `post_save` handlers receive the list of written fields instead of `None`.
360
+ - The last write wins between a form's GET and its POST. A field the user did not touch is not written.
361
+ But if another user changed a field after this form was loaded, and this user saves the form with that
362
+ field still showing the old value, the old value is written back. Django's admin behaves the same way.
363
+ History shows it.
364
+ - The database's own rejections (unique, foreign key, not-null, field validators) are shown as an error
365
+ on the form. Any other error is a 500 page with the traceback in the log (logger `devadmin`).
366
+ - An overridden `save_model` or `delete_model`, and an action, run outside any transaction the panel
367
+ opens. Host services open their own transactions and send side effects (queue messages, emails) after
368
+ their commit; wrapping them would turn their commit into a savepoint and fire those side effects
369
+ before the real commit. The panel snapshots the rows before the call, reloads them after it, and
370
+ records the difference it observed in a separate step. So a crash between the two loses that one
371
+ history entry, and a call that fails part-way can leave partial effects.
372
+ - When an overridden `save_model` or an action raises, the panel shows the error and records nothing,
373
+ so the partial effects of the failed call are not in history; a failed action's message says that
374
+ some changes may have been applied. An overridden `delete_model` without `transactional` is observed
375
+ even when it fails; see [With an overridden `delete_model`](#with-an-overridden-delete_model).
376
+ - Set `transactional = True` on the class, or `transactional=True` on an action, when the code does
377
+ plain ORM writes only. It then runs inside one transaction with its history, like the panel's own
378
+ writes.
379
+ - For a create, an overridden `save_model` must return the created object. If it returns `None`, the
380
+ row is saved but no history is recorded, and the panel says so.
381
+ - History for an action covers the selected rows only: a row that changed is recorded as an update, a
382
+ row that disappeared as a delete. Rows of other models the action changed are not recorded.
383
+ - A decimal value that needs more digits than Python's decimal context precision (28 by default,
384
+ counting the field's decimal places) is refused on create and update with `<Field> is out of range`,
385
+ before anything is written. A decimal error raised by your own `save()` or `pre_save` code is not
386
+ converted and surfaces as itself.
387
+
388
+ ## How the panel deletes
389
+
390
+ - Delete is available on every model by default and is a real delete. For "deactivate" instead,
391
+ override `delete_model` or add an action. `read_only_models` and `has_delete_permission` turn delete
392
+ off.
393
+ - Deleting is two steps. The confirmation page lists the rows the database will delete by cascade, the
394
+ rows whose reference will be set to empty, and the rows that block the delete, grouped by model, the
395
+ first 100 per model with a count of the rest.
396
+ - The page shows the display text of those related rows even for models the user may not view
397
+ (without a link), because the database removes them regardless and the page must say what will
398
+ happen. Form pages, by contrast, show only the stored key of a foreign-key target the user may not
399
+ view.
400
+ - Many-to-many links are counted on the page only for relations whose link rows the database removes
401
+ by cascade. They are not recorded in history. Deleting an object that still has a many-to-many link
402
+ declared with `on_delete=RESTRICT` (or `NO_ACTION`) is refused by the database, and the panel shows
403
+ the refusal.
404
+ - On confirmation, inside one transaction, the related rows are collected again, every affected row is
405
+ snapshotted, the object is deleted, and the object, every cascaded row and every unlinked row are
406
+ recorded under one history action.
407
+ - A delete that would affect more than `max_cascade_rows` (default 1000) related rows is refused with
408
+ the totals per model. A cleanup of that size belongs in a script.
409
+ - A delete is refused when blocking rows exist, when it would cascade into a read-only model, and when
410
+ it would cascade into a model the user may not delete from. A model in `exclude_models` never stops a
411
+ cascade: its rows are deleted and recorded like any other.
412
+ - There is no row lock. Rows another transaction creates between the check and the delete are removed
413
+ by the database's cascade without a history record.
414
+ - "Delete selected" on the list page uses the same flow for the whole selection.
415
+
416
+ ### With an overridden `delete_model`
417
+
418
+ - Blocking rows are shown but do not stop the call, since your routine may deal with them. The other
419
+ refusals above still apply.
420
+ - Before calling your routine the panel collects: the selected objects, their cascade closure, the rows
421
+ a plain delete would unlink, and up to 100 rows that would block a plain delete. After the routine
422
+ returns it reads those rows again and records what it finds, under one action: a row that is gone is
423
+ a delete, a row that changed is an update (a soft delete, for example). This holds with and without
424
+ `transactional`.
425
+ - Anything the routine touches outside that set is not recorded: other tables, children of blocking
426
+ rows, blocking rows beyond the first 100. A routine that does more should write its own history with
427
+ [`devadmin.history.action`](#recording-history-from-your-own-code).
428
+ - The message comes from what was observed. A soft delete reads `<Model> "<object>" was changed by its
429
+ delete routine.`, not "was deleted"; a routine that changed nothing says so.
430
+ - When a routine without `transactional` raises part-way, the panel reads the collected rows again all
431
+ the same and records what was already done under an action with the summary
432
+ `delete (failed part-way)`. The error page says how many objects and related rows were affected
433
+ before the error. With `transactional = True` a failure rolls everything back and nothing is
434
+ recorded.
435
+
436
+ ## History
437
+
438
+ ### What is recorded
439
+
440
+ - Every create, update and delete made through the panel, and every action that changed a selected
441
+ row.
442
+ - Every login and failed login, as an entry with no object changes (shown under "Recent actions").
443
+ - Every `devadmin grant` and `devadmin revoke` that changed the access flag.
444
+ - Changes your own code records with `devadmin.history.action` (below).
445
+
446
+ Changes made anywhere else are not recorded: devadmin uses no ORM signals.
447
+
448
+ ### What an entry contains
449
+
450
+ An entry is one action with one change per affected object.
451
+
452
+ - The action: time, actor (id and a text snapshot; there is no foreign key to the user table, actor
453
+ `system` when there is none), kind (`create`, `update`, `delete`, `action`, `custom`, `login`,
454
+ `login_failed`), summary, source (`panel` or `code`), client address and a JSON `meta`.
455
+ - Each change: model key, primary key as text, the object's text representation, the operation
456
+ (`create`, `update` or `delete`), the changed fields with their old and new values, a snapshot of the
457
+ full row (after a create or update, before a delete), and the label and type of every field at the
458
+ time of writing.
459
+
460
+ Values are stored in a JSON form that describes itself: decimals and dates as strings, enums as value
461
+ and label, foreign keys as the target's key and text, so they still read correctly after the target is
462
+ deleted.
463
+
464
+ History is rendered from the stored rows only and never loaded back into model classes, so it stays
465
+ readable after schema changes. A field that no longer exists is shown with its stored label and marked
466
+ "(removed)".
467
+
468
+ Sensitive fields are masked: a change records only that the field changed, with no values, and
469
+ snapshots hold no value for them. `exclude` is a form-layout option, not access control: fields it
470
+ removes from the form still appear in history. Use `sensitive_patterns` to hide a value everywhere.
471
+
472
+ ### History pages
473
+
474
+ - Each object's change page links to its history, newest first, at
475
+ `<mount>/m/<model key>/<primary key>/history`. The page opens on the same rule as the change page:
476
+ change or view permission on the object.
477
+ - The history of a deleted object stays reachable at that address, with the line
478
+ "This object no longer exists.".
479
+ - If the row exists but cannot be loaded (for example, its stored enum value is no longer in the
480
+ enum), the page shows the stored history with the line "This object could not be loaded.".
481
+ - If the model's admin class overrides `has_view_permission` or `get_queryset_filters`, the history
482
+ of a deleted row and of a row that cannot be loaded answers 404 instead, because the per-object
483
+ rule cannot be evaluated. A row outside `get_queryset_filters` also answers 404.
484
+ - `<mount>/history` ("Recent actions") lists recent actions across all models and is open to every
485
+ panel user. Action summaries written by host code and other users' display names are visible there
486
+ to all of them. It decides by model-level view permission only, so the display text of a row hidden
487
+ by an object-level rule or by `get_queryset_filters` can appear there; its link then answers 404.
488
+
489
+ ### Recording history from your own code
490
+
491
+ `devadmin.history.action(...)` lets service code write to the same history:
492
+
493
+ ```python
494
+ from tortoise.transactions import in_transaction
495
+
496
+ from devadmin import history
497
+ from myproject.models import Order, Status
498
+
499
+
500
+ async def cancel_order(order_id: int, actor=None) -> None:
501
+ async with in_transaction():
502
+ order = await Order.get(id=order_id)
503
+ async with history.action(actor=actor, summary="Cancelled by support") as act:
504
+ before = history.snapshot(order)
505
+ order.status = Status.cancelled
506
+ await order.save()
507
+ await act.record_update(order, before=before)
508
+ ```
509
+
510
+ - `history.action(actor=, summary=, kind="custom", source="code", ip=None, meta=None)`. `actor` is a
511
+ user object or `None` for `system`. `kind` and `source` take the values listed above.
512
+ - Inside the block, `await act.record_update(obj, before=snapshot)` records an update; take the
513
+ snapshot with `history.snapshot(obj)` before changing the object. `await act.record_create(obj)`
514
+ records a new row. An update that changed nothing records nothing.
515
+ - The block writes its entry when it ends. It joins the transaction your code has open, so the data and
516
+ the history commit or roll back together. With no transaction open, your writes and the history entry
517
+ commit separately.
518
+ - Nested blocks merge into the outer action. An inner block that raises, where the exception is then
519
+ caught, drops its records while its data writes may still commit. Run such inner work inside
520
+ `config.adapter.atomic()` so that its writes roll back with it.
521
+ - `devadmin.history` works in a process that has called `create_admin`; otherwise it raises
522
+ `RuntimeError("devadmin is not configured")`. If a process creates more than one panel, it is bound
523
+ to the first, and code that records for another panel uses `admin.state.devadmin.history`.
524
+ - A service that records its own history and is called from a panel action or an overridden
525
+ `save_model` produces two entries for the same change: its own, and the panel's.
526
+
527
+ ### Retention and tables
528
+
529
+ Nothing is purged automatically. `devadmin purge-history` is the only thing that deletes history; see
530
+ [Command line](#command-line).
531
+
532
+ The tables are `devadmin_action` (one row per action) and `devadmin_change` (one row per affected
533
+ object).
534
+
535
+ ## Access and security
536
+
537
+ ### Who can log in
538
+
539
+ - Login uses your own user table: `user_model`, `login_field`, `password_field`, your
540
+ `verify_password(plain, hashed)`, and one boolean column, `access_flag` (`is_superuser` by default).
541
+ If the model has an `is_active` field, it must be true as well.
542
+ - The login is matched exactly first; if no row matches, a single case-insensitive match is accepted.
543
+ - Never let your API write the access flag. Grant it only with `devadmin grant` or from inside the
544
+ panel, where the change is recorded in history.
545
+ - The panel has its own signed session cookie, scoped to the mount path, `HttpOnly`, `SameSite=Strict`
546
+ and `Secure` unless `secure_cookies=False`. It lasts `session_seconds` (8 hours by default) from login
547
+ and is not extended by activity. Your API's tokens never open the panel.
548
+ - The user row and the access flag are checked again on every request, so revoking the flag ends access
549
+ at once.
550
+ - The session holds a short fingerprint of the user's stored password hash, checked on every request.
551
+ A password change ends every existing session; logout clears the cookie on this browser only;
552
+ revoking the access flag ends access at once. A user without a stored password hash cannot hold a
553
+ session. There is no other server-side session revocation.
554
+
555
+ ### Password checks and login floods
556
+
557
+ - A synchronous `verify_password` runs in a worker thread, so it must be thread-safe and must not touch
558
+ the ORM. Use `async def` for a verifier that needs the event loop. Login attempts queue in the default
559
+ thread pool. An exception in `verify_password` counts as a wrong password.
560
+ - `login_rate_limiter` is the protection against login floods: an async callable that receives the
561
+ request and the typed login, stripped of surrounding whitespace and case-folded (so `" ROOT@B.UZ"`
562
+ arrives as `"root@b.uz"`), and returns `False` to refuse (the page answers 429). Without one, failed
563
+ logins are unbounded and each one writes a history row. Consider a rate limiter on the login route of
564
+ the mount (`<mount>/login`) as well.
565
+
566
+ ### Network and requests
567
+
568
+ - `allowed_ips` limits the panel to addresses or networks. Behind a proxy, give `client_ip`, a function
569
+ that returns the real client address of a request; only your project knows how many proxies sit in
570
+ front of it. The same address is stored with each history entry.
571
+ - One guard handles every request to the panel: the IP allowlist, authentication, a CSRF token on
572
+ every request other than GET, HEAD and OPTIONS, and security headers (`Cache-Control: no-store`,
573
+ `X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: same-origin`, and the
574
+ Content-Security-Policy
575
+ `default-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'none'`). WebSocket
576
+ connections to the panel are refused.
577
+ - Unknown query parameters, unknown sort columns and undeclared filters are answered with 400.
578
+
579
+ ### Sensitive fields and permissions
580
+
581
+ - A field whose name contains one of `sensitive_patterns` (`password`, `secret`, `token`, `hash` by
582
+ default) is hidden from lists and forms and masked in history. It cannot be named in `list_display`,
583
+ `search_fields`, `list_filter`, `fields`, `fieldsets` or `readonly_fields`. Passwords therefore cannot
584
+ be set from the panel. A model's own primary key is still shown and searchable when its name matches.
585
+ - A user who passes login can do everything by default. `read_only_models`, `exclude_models` and the
586
+ `has_*_permission` methods narrow that.
587
+ - `get_queryset_filters` scopes the rows the panel reaches: the list page, foreign-key autocomplete,
588
+ bulk actions, and the change, delete and history pages, which answer 404 for a row outside it, the
589
+ same as for a missing row. An edit may move a row out of the scope. The history of a deleted row is
590
+ hidden (404) for an admin class that defines `get_queryset_filters`. It is still a row scope, not a
591
+ permission system: to refuse a row by rule, use the `has_*_permission` methods, which receive the
592
+ object.
593
+ - Every panel user can read Recent actions; see [History pages](#history-pages).
594
+
595
+ ## Command line
596
+
597
+ Access to the panel is one boolean column on your user table (`access_flag`, default `is_superuser`).
598
+ Never make that column writable through your own API: grant it with this command, or from inside the
599
+ panel.
600
+
601
+ ```bash
602
+ devadmin grant <login> --config myproject.admin_panel:config
603
+ devadmin grant <login> --ignore-case --config myproject.admin_panel:config
604
+ devadmin revoke <login> --config myproject.admin_panel:config
605
+ devadmin purge-history --older-than 365d --config myproject.admin_panel:config
606
+ ```
607
+
608
+ `python -m devadmin ...` works the same way.
609
+
610
+ `--config` is required on every command. It is `module:attribute`, imported with the current directory
611
+ on `sys.path` (run it from your project root). The attribute is either an `AdminConfig` or a callable
612
+ with no arguments (sync or async) that returns one.
613
+
614
+ The command does not start your ORM. Give the config a `startup` and a `shutdown` coroutine, as in the
615
+ [Quick start](#quick-start); the command awaits `startup()` before its work and `shutdown()` afterwards,
616
+ even when the work fails. Without a `startup` that initialises Tortoise, `grant` fails with
617
+ `error: AdminConfig.user_model: unknown model 'models.User'` and similar lines, because no model is
618
+ known yet.
619
+
620
+ **grant** needs the login exactly as stored. If the only match differs in case, nothing is changed and
621
+ the command fails with `did you mean <stored login>?`; re-run with that exact value, or pass
622
+ `--ignore-case` to accept that single case-insensitive match (the result line then ends with
623
+ `(matched case-insensitively)`). **revoke** accepts an exact match or, if there is none, a single
624
+ case-insensitive match without a flag, since it only takes access away. When several users match, both
625
+ commands refuse and change nothing.
626
+
627
+ Both set the access flag and record the change in the history (actor `system`, summary `grant via CLI`
628
+ or `revoke via CLI`) in one transaction. Running them twice is harmless: a user who already has the
629
+ requested value is left untouched. `grant` warns when the account is inactive or has no password,
630
+ because it cannot log in to the panel until that is fixed. `revoke` never deletes anything.
631
+
632
+ **purge-history** deletes whole actions, with their changes, older than the given age, in batches.
633
+ `--older-than` takes a whole number of days written as `<N>d`. A value under 30 days also needs
634
+ `--yes`. Schedule it from your host (cron, a scheduled task), for example once a day:
635
+
636
+ ```bash
637
+ devadmin purge-history --older-than 365d --config myproject.admin_panel:config
638
+ ```
639
+
640
+ | Exit code | Meaning |
641
+ |---|---|
642
+ | `0` | Success. |
643
+ | `1` | The command failed: unknown, ambiguous or only case-insensitively matching login on `grant`; the config cannot be loaded or is invalid; startup, shutdown or the database failed. The message says which. |
644
+ | `2` | Bad command-line usage. |
645
+ | `130` | Interrupted (Ctrl-C). Check the result in the panel or re-run the command: it is safe to repeat. |
646
+
647
+ Errors are one line on stderr starting with `error: `, warnings start with `warning: `. Add
648
+ `--traceback` to see the full traceback of an unexpected error.
649
+
650
+ ## Limitations of 0.1.0
651
+
652
+ - The interface is in English only.
653
+ - Rows cannot be edited on the list page. There are no inlines.
654
+ - There is no revert and no recovery of deleted objects. The stored history has the data for both.
655
+ - Many-to-many relations are shown read-only, and their link rows are not recorded in history.
656
+ - There is no CSV import or export.
657
+ - Tortoise ORM is the only adapter. The adapter interface is internal and may change.
658
+ - History tables and your models must share one database connection.
659
+ - A row whose primary key is exactly `.` or `..` cannot be opened: browsers normalise such URL
660
+ segments away.
661
+ - A foreign key to a model whose own primary key is a one-to-one relation is shown as unsupported,
662
+ because Tortoise 0.25 creates no column for it.
663
+ - `list_per_page` has no upper bound, but an action takes at most about 1000 selected rows at once (the
664
+ form parser's field limit), and there is no "select all rows across pages".
665
+ - History shows the values of fields hidden from the form with `exclude` (see [History](#history)).
666
+ - The history pages do not show the client address, and there is no page for a single action.
667
+ - Recent actions loads every change of each action it lists, so an action with thousands of changes
668
+ (a large delete, for example) makes that page heavy.
669
+ - On SQLite, Tortoise returns decimals without trailing zeros, so forms and history show `19.5` for a
670
+ stored `19.50`, and history can show exponent form such as `1E+1` for `10.00`. On PostgreSQL,
671
+ Tortoise passes the database's decimal through unchanged, with its stored scale.
672
+ - Dates and times are shown in UTC, in history and in forms.
673
+ - Nothing deletes history except `purge-history`.
674
+
675
+ ## Development
676
+
677
+ Install the development environment (Poetry creates `.venv` inside the project) and run the tests on
678
+ an in-memory SQLite database:
679
+
680
+ ```bash
681
+ poetry install
682
+ .venv/bin/python -m pytest -q
683
+ ```
684
+
685
+ To run them on PostgreSQL, point `DEVADMIN_TEST_DB_URL` at an empty database used only for tests. The
686
+ fixtures create and drop their tables in it, and tests marked `postgres`, which are skipped otherwise,
687
+ run as well:
688
+
689
+ ```bash
690
+ DEVADMIN_TEST_DB_URL="postgres://<user>@localhost:5432/devadmin_test" .venv/bin/python -m pytest -q
691
+ ```
692
+
693
+ `tests/app/server.py` is a demo host with seeded data. It creates a fresh SQLite file in the system
694
+ temporary directory at every start and removes it on exit:
695
+
696
+ ```bash
697
+ .venv/bin/python -m uvicorn tests.app.server:app --reload
698
+ ```
699
+
700
+ Open `http://127.0.0.1:8000/dev-admin/` and log in as `root@b.uz` with password `pw`. `user@b.uz` with
701
+ the same password has no access.
702
+