hxadmin 0.2.0__tar.gz → 0.2.1__tar.gz

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 (122) hide show
  1. {hxadmin-0.2.0 → hxadmin-0.2.1}/CHANGELOG.md +16 -0
  2. {hxadmin-0.2.0 → hxadmin-0.2.1}/PKG-INFO +7 -7
  3. {hxadmin-0.2.0 → hxadmin-0.2.1}/README.md +6 -6
  4. {hxadmin-0.2.0 → hxadmin-0.2.1}/docs/actions.md +4 -2
  5. {hxadmin-0.2.0 → hxadmin-0.2.1}/docs/auth.md +7 -3
  6. {hxadmin-0.2.0 → hxadmin-0.2.1}/docs/export.md +4 -4
  7. {hxadmin-0.2.0 → hxadmin-0.2.1}/docs/forms.md +9 -9
  8. {hxadmin-0.2.0 → hxadmin-0.2.1}/docs/getting-started.md +2 -2
  9. {hxadmin-0.2.0 → hxadmin-0.2.1}/docs/lists.md +15 -11
  10. {hxadmin-0.2.0 → hxadmin-0.2.1}/docs/pages.md +2 -2
  11. {hxadmin-0.2.0 → hxadmin-0.2.1}/docs/templates.md +6 -6
  12. {hxadmin-0.2.0 → hxadmin-0.2.1}/docs/views.md +31 -3
  13. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/forms.py +0 -2
  14. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/routes.py +1 -1
  15. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/_macros.html +6 -5
  16. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_delete.py +11 -0
  17. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_detail.py +28 -0
  18. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_forms.py +7 -1
  19. {hxadmin-0.2.0 → hxadmin-0.2.1}/zensical.toml +2 -0
  20. {hxadmin-0.2.0 → hxadmin-0.2.1}/.gitignore +0 -0
  21. {hxadmin-0.2.0 → hxadmin-0.2.1}/LICENSE +0 -0
  22. {hxadmin-0.2.0 → hxadmin-0.2.1}/docs/index.md +0 -0
  23. {hxadmin-0.2.0 → hxadmin-0.2.1}/pyproject.toml +0 -0
  24. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/__init__.py +0 -0
  25. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/actions.py +0 -0
  26. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/admin.py +0 -0
  27. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/components.py +0 -0
  28. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/deps.py +0 -0
  29. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/export.py +0 -0
  30. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/fields.py +0 -0
  31. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/filters.py +0 -0
  32. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/icons.py +0 -0
  33. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/nav.py +0 -0
  34. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/origin.py +0 -0
  35. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/pages.py +0 -0
  36. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/pk.py +0 -0
  37. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/py.typed +0 -0
  38. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/query.py +0 -0
  39. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/static/hxadmin.css +0 -0
  40. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/static/src/hxadmin.css +0 -0
  41. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/static/vendor/air-datepicker.LICENSE +0 -0
  42. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/static/vendor/air-datepicker.css +0 -0
  43. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/static/vendor/air-datepicker.min.js +0 -0
  44. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/static/vendor/alpine-anchor.min.js +0 -0
  45. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/static/vendor/alpine-focus.min.js +0 -0
  46. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/static/vendor/alpine-plugins.LICENSE +0 -0
  47. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/static/vendor/alpine.min.js +0 -0
  48. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/static/vendor/htmx.min.js +0 -0
  49. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/static/vendor/lucide.LICENSE +0 -0
  50. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/static/vendor/lucide.json +0 -0
  51. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/_palette.html +0 -0
  52. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/components/badge.html +0 -0
  53. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/components/button.html +0 -0
  54. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/components/card.html +0 -0
  55. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/components/date.html +0 -0
  56. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/components/dialog.html +0 -0
  57. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/components/feedback.html +0 -0
  58. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/components/icon.html +0 -0
  59. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/components/menu.html +0 -0
  60. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/components/misc.html +0 -0
  61. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/dashboard.html +0 -0
  62. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/detail/_panel.html +0 -0
  63. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/detail/_related_plain.html +0 -0
  64. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/detail.html +0 -0
  65. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/error.html +0 -0
  66. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/form/_field.html +0 -0
  67. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/form/_fields.html +0 -0
  68. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/form/_options.html +0 -0
  69. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/form.html +0 -0
  70. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/layout.html +0 -0
  71. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/list/_pagination.html +0 -0
  72. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/list/_table.html +0 -0
  73. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/list/_toolbar.html +0 -0
  74. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/list.html +0 -0
  75. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/login.html +0 -0
  76. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/templates/hxadmin/page.html +0 -0
  77. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/toasts.py +0 -0
  78. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/users.py +0 -0
  79. {hxadmin-0.2.0 → hxadmin-0.2.1}/src/hxadmin/views.py +0 -0
  80. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/__init__.py +0 -0
  81. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/conftest.py +0 -0
  82. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/html.py +0 -0
  83. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/js.py +0 -0
  84. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_action_permissions.py +0 -0
  85. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_action_routes.py +0 -0
  86. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_action_ui.py +0 -0
  87. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_actions.py +0 -0
  88. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_admin.py +0 -0
  89. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_auth.py +0 -0
  90. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_badges.py +0 -0
  91. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_components.py +0 -0
  92. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_create_edit.py +0 -0
  93. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_dashboard.py +0 -0
  94. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_date_input.py +0 -0
  95. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_dependencies.py +0 -0
  96. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_export.py +0 -0
  97. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_export_routes.py +0 -0
  98. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_fields.py +0 -0
  99. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_filter_ui.py +0 -0
  100. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_filters.py +0 -0
  101. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_icons.py +0 -0
  102. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_list.py +0 -0
  103. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_list_contracts.py +0 -0
  104. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_login.py +0 -0
  105. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_lookup.py +0 -0
  106. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_nav.py +0 -0
  107. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_origin.py +0 -0
  108. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_package.py +0 -0
  109. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_pages.py +0 -0
  110. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_palette.py +0 -0
  111. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_query.py +0 -0
  112. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_render.py +0 -0
  113. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_save_feedback.py +0 -0
  114. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_session_user.py +0 -0
  115. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_shell.py +0 -0
  116. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_static.py +0 -0
  117. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_table_models.py +0 -0
  118. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_template_names.py +0 -0
  119. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_toasts.py +0 -0
  120. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_users.py +0 -0
  121. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_version.py +0 -0
  122. {hxadmin-0.2.0 → hxadmin-0.2.1}/tests/test_views.py +0 -0
@@ -2,6 +2,22 @@
2
2
 
3
3
  All notable changes to this project are documented in this file.
4
4
 
5
+ ## [0.2.1] - 2026-10-28
6
+
7
+ ### Bug fixes
8
+
9
+ - An empty text field on a new row now gets the column's default
10
+ - A delete refused because other rows refer to it shows an error toast instead of an error page
11
+ - Hide a detail page's tab for a relation whose view the user cannot access
12
+ - Show a relation as plain text on the detail page when its view is not accessible
13
+
14
+ ### Documentation
15
+
16
+ - Say the Log out button sits at the bottom of the sidebar
17
+ - Show the GitHub repository and latest release in the docs header
18
+ - Correct the docs where they no longer match the code
19
+ - Document the ModelView helpers and resolved attributes templates use
20
+
5
21
  ## [0.2.0] - 2026-10-27
6
22
 
7
23
  ### Features
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: hxadmin
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: Admin interface for FastAPI and SQLAlchemy 2.0+, built with Tailwind CSS and htmx
5
5
  Project-URL: Homepage, https://github.com/gledi-ai/hxadmin
6
6
  Project-URL: Documentation, https://gledi-ai.github.io/hxadmin/
@@ -63,21 +63,21 @@ admin = HxAdmin(app, session=get_session, auth=current_admin_user, title="My adm
63
63
  @admin.register
64
64
  class UserView(ModelView[User]):
65
65
  model = User
66
- list_columns = ("email", "name", "group")
66
+ list_columns = ("email", "name", "active")
67
67
  searchable = ("email", "name")
68
- list_filters = ("active", "group")
69
- export_formats = ("csv", "xlsx")
68
+ list_filters = ("active",)
69
+ export_formats = ("csv",)
70
70
  ```
71
71
 
72
72
  `session` yields an `AsyncSession`; `auth` returns the current user or raises `HTTPException(status.HTTP_401_UNAUTHORIZED)`. Open `/admin/`.
73
73
 
74
- Documentation: [gledi-ai.github.io/hxadmin](https://gledi-ai.github.io/hxadmin/) (build locally with `nox -s docs`). Try everything in the demo: `uv run python -m demos.orm`, then open http://127.0.0.1:8001/admin/. For projects built on plain Core `Table`s instead of ORM models, see `uv run python -m demos.tables` (http://127.0.0.1:8002/admin/).
74
+ Documentation: [gledi-ai.github.io/hxadmin](https://gledi-ai.github.io/hxadmin/) (build locally with `nox -s docs`). Try everything in the demo: `make demo`, then open http://127.0.0.1:8001/admin/ and sign in as `ada@example.com` / `demo`. For projects built on plain Core `Table`s instead of ORM models, see `make demo/tables` (http://127.0.0.1:8002/admin/, `admin@example.com` / `demo`).
75
75
 
76
76
  ## Development
77
77
 
78
78
  ```bash
79
- uv sync # installs the dev group (lint + test + ipython)
80
- prek install # git hooks: ruff, pyrefly, uv-lock
79
+ uv sync # installs the dev group (lint + test + demo + ipython)
80
+ prek install # git hooks: ruff, pyrefly, zizmor, uv-lock, Conventional Commits
81
81
  nox # lint + tests on every supported Python
82
82
  nox -s tests-3.14 # single Python version
83
83
  nox -s tests_lowest # tests against the lowest supported dependency versions
@@ -24,21 +24,21 @@ admin = HxAdmin(app, session=get_session, auth=current_admin_user, title="My adm
24
24
  @admin.register
25
25
  class UserView(ModelView[User]):
26
26
  model = User
27
- list_columns = ("email", "name", "group")
27
+ list_columns = ("email", "name", "active")
28
28
  searchable = ("email", "name")
29
- list_filters = ("active", "group")
30
- export_formats = ("csv", "xlsx")
29
+ list_filters = ("active",)
30
+ export_formats = ("csv",)
31
31
  ```
32
32
 
33
33
  `session` yields an `AsyncSession`; `auth` returns the current user or raises `HTTPException(status.HTTP_401_UNAUTHORIZED)`. Open `/admin/`.
34
34
 
35
- Documentation: [gledi-ai.github.io/hxadmin](https://gledi-ai.github.io/hxadmin/) (build locally with `nox -s docs`). Try everything in the demo: `uv run python -m demos.orm`, then open http://127.0.0.1:8001/admin/. For projects built on plain Core `Table`s instead of ORM models, see `uv run python -m demos.tables` (http://127.0.0.1:8002/admin/).
35
+ Documentation: [gledi-ai.github.io/hxadmin](https://gledi-ai.github.io/hxadmin/) (build locally with `nox -s docs`). Try everything in the demo: `make demo`, then open http://127.0.0.1:8001/admin/ and sign in as `ada@example.com` / `demo`. For projects built on plain Core `Table`s instead of ORM models, see `make demo/tables` (http://127.0.0.1:8002/admin/, `admin@example.com` / `demo`).
36
36
 
37
37
  ## Development
38
38
 
39
39
  ```bash
40
- uv sync # installs the dev group (lint + test + ipython)
41
- prek install # git hooks: ruff, pyrefly, uv-lock
40
+ uv sync # installs the dev group (lint + test + demo + ipython)
41
+ prek install # git hooks: ruff, pyrefly, zizmor, uv-lock, Conventional Commits
42
42
  nox # lint + tests on every supported Python
43
43
  nox -s tests-3.14 # single Python version
44
44
  nox -s tests_lowest # tests against the lowest supported dependency versions
@@ -48,6 +48,8 @@ class UserView(ModelView[User]):
48
48
  return ActionResult.message(f"Reset link sent to {email}.", level="info")
49
49
  ```
50
50
 
51
+ `@action(name, *, label=None, bulk=False, confirm=None, method="POST")` marks a method as an action. `name` (letters, digits, `_` and `-`) is part of the action's URL and must be unique within the view; `label` defaults to the name capitalised, so `reset_password` shows as "Reset password". Handlers must be `async def`; anything else raises at registration.
52
+
51
53
  `send_password_reset` and the `/reset` page that redeems the token are your application's; hxadmin has no mail or password-reset support of its own.
52
54
 
53
55
  ## How changes are saved
@@ -83,7 +85,7 @@ Return one of:
83
85
 
84
86
  Returning anything else counts as a failure. The toast shows in the bottom-right corner with an icon per level. Toasts pause while hovered, and error toasts stay until dismissed.
85
87
 
86
- A row action that deletes its object should return a redirect, since there is no detail page left to show; if it returns a message, hxadmin falls back to the list:
88
+ A row action that deletes its object should return a redirect, since there is no detail page left to show; if a POST action returns a message, hxadmin falls back to the list:
87
89
 
88
90
  ```python
89
91
  @action("purge", label="Delete with tasks", confirm="Delete this user and all their tasks?")
@@ -120,7 +122,7 @@ class UserView(ModelView[User]):
120
122
 
121
123
  A GET action runs from a plain link, so it must not change data: another site could trigger it (see [Cross-site requests](auth.md#cross-site-requests)). Use POST for anything with side effects.
122
124
 
123
- Handlers get objects without eager-loaded relationships, and async SQLAlchemy cannot lazy-load them: `await session.refresh(obj, ["tasks"])` loads one before you touch it, as above.
125
+ Handlers get objects without eager-loaded relationships (unless your `get_query` adds loader options), and async SQLAlchemy cannot lazy-load them: `await session.refresh(obj, ["tasks"])` loads one before you touch it, as above.
124
126
 
125
127
  ## Permissions
126
128
 
@@ -7,7 +7,7 @@ admin = HxAdmin(
7
7
  auth=current_admin_user, # dependency returning the user, or raising HTTPException
8
8
  prefix="/admin",
9
9
  login_url="/login", # optional
10
- logout_url="/logout", # optional; shown in the top bar
10
+ logout_url="/logout", # optional; Log out button at the bottom of the sidebar
11
11
  trusted_origins=(), # optional; other origins allowed to send writes
12
12
  )
13
13
  ```
@@ -22,7 +22,7 @@ FastAPI resolves a dependency once per request, so when your `auth` (or a custom
22
22
 
23
23
  `auth` runs on every admin request. Its return value is available as `request.state.hxadmin_user` and as `user` in templates. The user panel at the bottom of the sidebar shows `user.name` (an attribute or a mapping key) when it is set, otherwise `str(user)`, with initials derived from it. Any return value works: `None` or a bool (an `auth` that only answers "allowed") shows a generic avatar with no name.
24
24
 
25
- To deny access, raise `HTTPException(status.HTTP_401_UNAUTHORIZED)` or `HTTPException(status.HTTP_403_FORBIDDEN)` (`status` is `fastapi.status`). With `login_url` set, these send the browser to the login page (303, or `HX-Redirect` for htmx requests). Without it, they render an error page, keeping the exception's headers.
25
+ To deny access, raise `HTTPException(status.HTTP_401_UNAUTHORIZED)` or `HTTPException(status.HTTP_403_FORBIDDEN)` (`status` is `fastapi.status`). With `login_url` set, a 401 or 403 raised by `auth` sends the browser to the login page (a 303, or `HX-Redirect` for htmx requests). Once `auth` has returned a user, later 401s and 403s (`is_accessible`, custom pages, the cross-site check) render the error page instead, as do all of them without `login_url`, keeping the exception's headers.
26
26
 
27
27
  ### Example: HTTP Basic against the users table
28
28
 
@@ -113,9 +113,13 @@ import os
113
113
  from typing import Annotated
114
114
 
115
115
  from fastapi import Depends, HTTPException, status
116
+ from sqlalchemy.ext.asyncio import AsyncSession
116
117
  from starlette.middleware.sessions import SessionMiddleware
117
118
  from starlette.requests import Request
118
119
 
120
+ from myapp.db import get_session
121
+ from myapp.models import User
122
+
119
123
  app.add_middleware(SessionMiddleware, secret_key=os.environ["SESSION_SECRET"], https_only=True)
120
124
 
121
125
 
@@ -138,7 +142,7 @@ The admin is mounted inside `app`, so middleware added to `app` runs for admin r
138
142
 
139
143
  ### The sign-in page
140
144
 
141
- If your app has no login page of its own, `admin.render_login()` renders one in the admin's style (light and dark, `logo_url` and `title`, no sidebar). Its form posts `username` and `password` to the current path:
145
+ If your app has no login page of its own, `admin.render_login()` renders one in the admin's style (light and dark, `logo_url` and `title`, no sidebar). Its form posts `username` and `password` to the current path. Continuing the module above, with `verify_password` from the HTTP Basic example:
142
146
 
143
147
  ```python
144
148
  from fastapi import status
@@ -19,9 +19,9 @@ Listing `"xlsx"` without it installed raises `ImportError` when the view is regi
19
19
 
20
20
  ## What is exported
21
21
 
22
- The list footer links to `/{prefix}/{identity}/_export/csv` (and `xlsx`) with the current search, filters and sort, and the export contains every matching row across all pages. With rows checked, the selection bar offers an export of just those rows. Rows always come through `get_query`.
22
+ The **Export** menu in the list toolbar links to `/{prefix}/{identity}/_export/csv` (and `xlsx`) with the current search, filters and sort, and the export contains every matching row across all pages. With rows checked, the selection bar offers an export of just those rows, which `export_max_rows` does not limit. Rows always come through `get_query`.
23
23
 
24
- When more rows match than `export_max_rows`, no file is produced: the browser returns to the list with a warning toast.
24
+ When more rows match the search and filters than `export_max_rows`, no file is produced: the browser returns to the list with a warning toast.
25
25
 
26
26
  ## Cells
27
27
 
@@ -33,8 +33,8 @@ The header row has the field labels. A column with a `format_<name>` method expo
33
33
  | bool | `true` / `false` | boolean |
34
34
  | number | as written | number; NaN is `#NUM!`, infinity `#DIV/0!` |
35
35
  | date, datetime, time | ISO 8601 | date cell; aware datetimes converted to UTC |
36
- | enum | its value | text |
37
- | many-to-one relation | the related row's `display()` | text |
36
+ | enum | its value | its value: text, or a number for int-valued enums |
37
+ | many-to-one relation | the related row's `display()` (`str()` when its model has no view) | text |
38
38
  | to-many relation | number of rows | number |
39
39
  | JSON | JSON text | text |
40
40
 
@@ -2,16 +2,16 @@
2
2
 
3
3
  Create and edit forms are derived from the mapper:
4
4
 
5
- - autoincrement primary keys, foreign-key columns covered by a relationship, and columns of a type hxadmin has no input for (`LargeBinary`, `ARRAY`, `Interval`, ...) are skipped; naming such a column in `form_fields` raises at registration;
5
+ - autoincrement primary keys, foreign-key columns covered by a relationship, and columns of a type hxadmin has no input for (`LargeBinary`, `ARRAY`, `Interval`, ...) are skipped; naming a column of an unsupported type in `form_fields` raises at registration;
6
6
  - `String(n)` columns accept at most `n` characters, and integer columns the range of their type (`SmallInteger` 16-bit, `Integer` 32-bit, `BigInteger` 64-bit);
7
7
  - enum columns become selects, booleans checkboxes, dates and times the themed [date picker](#dates-and-times);
8
8
  - relationships become a search-as-you-type combobox, backed by the related view's `searchable` columns (without any, it matches each row's display text, scanning the first 2,000 rows, so give large related tables `searchable` columns): a single relation looks like a select showing the current value with a clear `×`, a multiple one shows its values as removable chips;
9
- - primary keys, including relationships whose foreign keys form the primary key, are read-only on edit.
9
+ - primary keys, including relationships whose foreign keys form the primary key, are left off the edit form.
10
10
 
11
11
  The form is a left-aligned column up to 720px wide. Short fields (selects, numbers, checkboxes, dates and times, single relations) sit two to a row from the `sm` breakpoint; text, JSON and multiple relations take the full width.
12
12
 
13
13
  ```python
14
- from hxadmin import Field
14
+ from hxadmin import Field, ModelView
15
15
 
16
16
 
17
17
  @admin.register
@@ -25,7 +25,7 @@ class UserView(ModelView[User]):
25
25
  )
26
26
  ```
27
27
 
28
- `form_fields` takes names or `Field(...)` overrides for `label`, `widget`, `required`, `help_text` and `readonly`, in the order the form shows them. A `Field`'s second argument, the kind, is required by its signature but replaced by the column's own kind, so it does not change the input; pass the column's kind (`"str"`, `"int"`, ...) for readability. Every name must be a column or relationship of the model: there are no form-only fields.
28
+ `form_fields` takes names or `Field(...)` overrides for `label`, `widget`, `required`, `help_text` and `readonly`, in the order the form shows them. `Field(...)` overrides apply to columns only; list relationships by name. A `Field`'s second argument, the kind, is required by its signature but replaced by the column's own kind, so it does not change the input; pass the column's kind (`"str"`, `"int"`, ...) for readability. Every name must be a column or relationship of the model: there are no form-only fields.
29
29
 
30
30
  To keep the derived fields and drop a few, use `form_exclude` instead:
31
31
 
@@ -40,7 +40,7 @@ Without it, `password_hash` would be an ordinary text input that stores whatever
40
40
 
41
41
  `widget` changes the HTML input only: `widget="email"` gets the browser's email keyboard and its own check, but the server still accepts any string. Validate on the server in `on_save` (below) or with a database constraint.
42
42
 
43
- An empty non-nullable input is left to the model default on create and reported as required on edit: on the docs models, leaving `priority` empty on a new task gives it the default `3`. `DateTime(timezone=True)` columns receive naive values from the datetime picker.
43
+ Strings arrive stripped of surrounding whitespace. A non-nullable column without a default is required. With a default, an empty input is left to the default on create (leaving `priority` empty on a new task gives it `3`); on edit it is reported as required, except on a text column, where it saves an empty string. `DateTime(timezone=True)` columns receive naive values from the datetime picker.
44
44
 
45
45
  Each field shows its label (with a red `*` when required), the input, the help text and then the error. The Cancel / Save footer sticks to the bottom of the viewport on long forms; the edit page title carries the row's `#pk`.
46
46
 
@@ -57,7 +57,7 @@ Date, datetime and time fields use a vendored [Air Datepicker](https://air-datep
57
57
 
58
58
  ## Saving
59
59
 
60
- Validation errors re-render the form in place with status 422, with each message under its field and form-level errors in an alert above the fields. On success, `on_save(request, session, obj, *, created)` runs, then hxadmin commits and redirects with a toast such as *Task "Write docs" created.*
60
+ Validation errors re-render the form in place with status 422, with each message under its field and form-level errors in an alert above the fields. On success, `on_save(request, session, obj, *, created)` runs, then hxadmin commits and redirects to the row's detail page (the list when `can_view` is off), or to a blank form after **Save and add another**, with a toast such as *Task “Write docs” created.*
61
61
 
62
62
  `on_save` runs after the form values are written onto `obj` and before anything is flushed, so it sees the new values and can still change them. `session` is the request's session, the same one hxadmin commits, so objects you add to it are saved with the row. On create, `obj` has no autoincrement primary key yet; `await session.flush()` assigns one if you need it.
63
63
 
@@ -70,17 +70,17 @@ from sqlalchemy import inspect
70
70
  from sqlalchemy.ext.asyncio import AsyncSession
71
71
  from starlette.requests import Request
72
72
 
73
- from hxadmin import FormError
73
+ from hxadmin import FormError, ModelView
74
74
  from myapp.models import Task
75
75
 
76
76
 
77
+ @admin.register
77
78
  class TaskView(ModelView[Task]):
78
79
  model = Task
79
80
 
80
81
  async def on_save(
81
82
  self, request: Request, session: AsyncSession, obj: Task, *, created: bool
82
83
  ) -> None:
83
- obj.title = obj.title.strip()
84
84
  due_changed = inspect(obj).attrs.due_date.history.has_changes()
85
85
  if due_changed and obj.due_date is not None and obj.due_date < date.today():
86
86
  raise FormError("Due date is in the past.", field="due_date")
@@ -92,4 +92,4 @@ The due-date check only runs when the date changed, so a task whose due date has
92
92
 
93
93
  The session is rolled back and the form re-renders with the message under `field`, or at the top of the form when `field` is omitted or not on the form. Integrity errors (such as a duplicate unique value) and values the database rejects also roll back and show a generic form-level error; the database's own message, which can name constraints and values, goes to the `hxadmin` logger instead. Any other exception rolls back and propagates: htmx requests get a "Something went wrong." toast, page loads the error page.
94
94
 
95
- Delete lives in the detail page's `⋯` menu and in each list row's menu, and asks first in the shared confirm dialog. Deleting runs `on_delete(request, session, obj)` first; a row that other rows still reference answers 409 with "other records still refer to it" (an error toast over htmx, else the error page).
95
+ Delete lives in the detail page's `⋯` menu and in each list row's menu, and asks first in the shared confirm dialog. Deleting runs `on_delete(request, session, obj)` first; a row that other rows still reference is kept, and an error toast says "other records still refer to it" (the route answers 409).
@@ -11,7 +11,7 @@ hxadmin needs Python 3.13+, FastAPI and SQLAlchemy 2.0+ with an async driver (`a
11
11
 
12
12
  ## The models in these docs
13
13
 
14
- The examples throughout these docs use the same three models, a small task tracker. They are the repository's demo models plus a few columns (`active`, `is_superuser`, `password_hash`, `archived`) and a `PasswordReset` table that later examples need:
14
+ The examples throughout these docs use the same three models, a small task tracker. They are the repository's demo models plus a few columns (`active`, `is_superuser`, `archived`) and a `PasswordReset` table that later examples need:
15
15
 
16
16
  ```python
17
17
  # myapp/models.py
@@ -180,7 +180,7 @@ The URL is used as given, so it must be served by your app (for example with Fas
180
180
  The repository ships a small todo app that exercises every feature:
181
181
 
182
182
  ```bash
183
- uv run python -m demos.orm
183
+ make demo # or: uv run --group demo python -m demos.orm
184
184
  ```
185
185
 
186
186
  Then open <http://127.0.0.1:8001/admin/>. The demo creates and seeds `demos/orm/demo.db` on first start. Sign in as `ada@example.com` with the password `demo`. `make demo/tables` runs a second demo built on plain Core `Table`s (<http://127.0.0.1:8002/admin/>, `admin@example.com` / `demo`).
@@ -4,18 +4,18 @@ The list page at `/{prefix}/{identity}/` searches, sorts, filters and paginates
4
4
 
5
5
  | Parameter | Meaning |
6
6
  |---|---|
7
- | `q` | Search over `searchable` columns |
8
- | `sort`, `dir` | Sort column and `asc` / `desc`; ties, and lists with no sort, are ordered by primary key |
7
+ | `q` | Search over `searchable` columns (without any, the search box is disabled) |
8
+ | `sort`, `dir` | Sort column and `asc` / `desc`; ties are broken by primary key; with no sort, rows keep `get_query`'s own order, then primary key |
9
9
  | `page`, `size` | Page number and page size (one of `page_size_options`) |
10
10
  | `f.<name>...` | Filters, below |
11
11
 
12
- Invalid values fall back to the defaults. Requests with `HX-Request: true` get only the table partial, plus out-of-band updates for the filter summaries, the Reset button and the export links, so an open filter popover stays open while the table refreshes.
12
+ Invalid values fall back to the defaults, and a page past the end shows the last page. Requests with `HX-Request: true` get only the table partial, plus out-of-band updates for the filter summaries, the Reset button and the export links, so an open filter popover stays open while the table refreshes.
13
13
 
14
14
  ## Table
15
15
 
16
- The header shows the plural name with the row count ("Tasks · 6", updated as you search and filter) and the New button. The table sits in a bordered card that scrolls within the viewport, with a sticky header. Columns size to their content; the primary column takes the remaining width and is the only link, to the detail page (when `can_view`). The primary column is the first text or many-to-one relation column of `list_columns` that is not the primary key, or the first column when there is none: with `list_columns = ("id", "title", "status")` it is `title`. To make a column the link, list a text column first or reorder them. Relations render as plain muted text, enums and declared bools as badges (see [Badges](views.md#badges)), other bools as a check or cross icon, and missing values as `—`. Numbers are right-aligned with tabular figures. Checked rows are highlighted.
16
+ The header shows the plural name with the row count ("Tasks · 6", updated as you search and filter) and the New button. The table sits in a bordered card that scrolls within the viewport, with a sticky header. Columns size to their content; the primary column takes the remaining width and is the only link, to the detail page (when `can_view`). The primary column is the first text or relation column of `list_columns` that is not the primary key. When there is none, the first column is the link and an empty column takes the remaining width. With `list_columns = ("id", "title", "status")` it is `title`. To make a column the link, list a text column first or reorder them. To-one relations render as plain muted text, to-many relations as their row count, enums and declared bools as badges (see [Badges](views.md#badges)), other bools as a check or cross icon, and missing values as `—`. Numbers are right-aligned with tabular figures. Checked rows are highlighted.
17
17
 
18
- With no rows, the table is replaced by an empty state: "No tasks yet" with a "New task" button, or "No tasks match these filters" with a "Reset filters" button when a search or filter is active.
18
+ With no rows, the table is replaced by an empty state: "No tasks yet" (with a "New task" button when `can_create`), or "No tasks match these filters" with a "Reset filters" button when a search or filter is active.
19
19
 
20
20
  Below the `sm` breakpoint, rows render as stacked cards instead: a checkbox, the primary column as the title, the next three list columns as `label: value` pairs, and the row menu. The search box shares the first toolbar row with Export, the filter buttons scroll horizontally on the row below, and a Select all checkbox sits above the cards.
21
21
 
@@ -39,17 +39,17 @@ With the [docs models](getting-started.md#the-models-in-these-docs), this gives
39
39
  | string, text, uuid, other types | text box | `f.title=report` | case-insensitive substring of the value cast to text |
40
40
  | many-to-one relation | checkboxes of related rows | `f.project=3` (primary key; `;`-joined if composite) | any checked row |
41
41
 
42
- Range bounds are written back the way their inputs write them (`2026-02-01` on a datetime becomes `2026-02-01T00:00`). A bound with a UTC offset on a column without time zone is converted to UTC. Values no database could compare, such as non-finite numbers, are ignored.
42
+ Range bounds are written back the way their inputs write them (`2026-02-01` on a datetime becomes `2026-02-01T00:00`). A datetime bound with a UTC offset on a column without time zone is converted to UTC; a time bound with an offset on such a column is ignored. Values no database could compare, such as non-finite numbers, are ignored.
43
43
 
44
44
  Nullable columns and optional relations get an extra **Empty** checkbox (`f.<name>.empty=1`) that also matches rows without a value. Different filters combine with AND.
45
45
 
46
46
  Relation filters offer the first 100 rows of the related model, through its view's `get_query` when it is registered, in that query's own order and then by primary key. If the related view is not accessible to the current user, the filter is hidden. Matching a checked row compares primary keys only; it narrows rows the list already shows and does not apply the related view's `get_query` again. Filters on to-many relations, on the side of a one-to-one without the foreign key, and on JSON columns are not supported and raise at registration.
47
47
 
48
- Each visible filter gets its own pill in the toolbar: dashed with a `+` icon and the label when inactive, solid with the label and a summary of the active value when it has one. The summary shows up to two values as badges (otherwise "N selected"), a range as `≥2`, `≤5` or `2–5`, and text as the quoted value, with "Empty" appended when set.
48
+ Each visible filter gets its own pill in the toolbar: dashed with a `+` icon and the label when inactive, solid with the label and a summary of the active value when it has one. The summary shows up to two values as badges (otherwise "N selected"), a range as `≥ 2`, `≤ 5` or `2–5`, and text as the quoted value, with "+ Empty" appended when set (or "Empty" alone).
49
49
 
50
- Clicking a pill opens its popover, and changes apply immediately:
50
+ Clicking a pill opens its popover, and changes apply immediately. Every popover ends with Empty (nullable filters only) and Clear:
51
51
 
52
- - choice and relation filters: a search box that narrows the options, a checkbox list, then Empty and Clear;
52
+ - choice and relation filters: a search box that narrows the options, then a checkbox list;
53
53
  - numeric ranges: From and To number inputs;
54
54
  - date, datetime and time ranges: From and To [date pickers](forms.md#dates-and-times), which submit ISO values (`2026-09-23`, `2026-09-23T14:30`, `14:30`) under the same `f.<name>.min` / `.max` names;
55
55
  - text: one "Contains…" input.
@@ -58,8 +58,12 @@ A Reset button appears once any filter is active. Sorting, paging, actions, expo
58
58
 
59
59
  ## Row menu
60
60
 
61
- Every row has a `⋯` button in its last column, always visible, opening a menu with View (when `can_view`), Edit (when `can_edit`), the row's permitted actions, a separator, then Delete in danger colour (when `can_delete`). Delete and actions with `confirm` open the shared confirm dialog; choosing any item closes the menu. The menu is keyboard-navigable: arrows move, Home and End jump, Esc closes and returns focus to the button.
61
+ When the view has Edit, Delete or a permitted row action, every row has a `⋯` button in its last column, always visible, opening a menu with View (when `can_view`), Edit (when `can_edit`), the row's permitted actions, a separator, then Delete in danger colour (when `can_delete`). Delete and actions with `confirm` open the shared confirm dialog; choosing any item closes the menu. The menu is keyboard-navigable: arrows move, Home and End jump, Esc closes and returns focus to the button.
62
+
63
+ ## Pagination
64
+
65
+ Below the table, "Showing 1–25 of 60" sits next to a Rows per page select (`page_size_options`, default `page_size`), First, Previous, Next and Last buttons, and "Page 1 of 3". Changing the page size returns to page 1.
62
66
 
63
67
  ## Bulk actions
64
68
 
65
- Checking one or more rows shows a floating bar centred at the bottom of the viewport: the selection count, the bulk actions as buttons, an Export menu for the selected rows when export is enabled, and a `✕` to clear the selection. It floats over the page without shifting the layout, and the select-all checkbox shows an indeterminate state when some but not all visible rows are checked. The selection covers the rows on screen: sorting, paging, filtering or a bulk action re-renders the table and clears it.
69
+ Rows have checkboxes only when the view has permitted bulk actions or `export_formats`. Checking one or more rows shows a floating bar centred at the bottom of the viewport: the selection count, the bulk actions as buttons, an Export menu for the selected rows when export is enabled, and a `✕` to clear the selection. It floats over the page without shifting the layout, and the select-all checkbox shows an indeterminate state when some but not all visible rows are checked. The selection covers the rows on screen: sorting, paging, filtering or a bulk action re-renders the table and clears it.
@@ -60,13 +60,13 @@ The templates go in the directory passed as `HxAdmin(templates_dir=...)`, and ex
60
60
  {% endblock %}
61
61
  ```
62
62
 
63
- The repository's demo has this exact pair of pages (`demos/orm/app.py`, `demos/orm/templates/`).
63
+ The repository's demo has these two pages (`demos/orm/app.py`, `demos/orm/templates/`).
64
64
 
65
65
  Handlers are ordinary `async` FastAPI endpoints (`Depends`, path and query parameters, `methods=("POST",)`), guarded by `auth`. A path parameter with a type, like `status: TaskStatus`, is validated by FastAPI: `/stats/nope` answers 422. Return `Page(template, context)` to render inside the admin shell, or any `Response` or JSON-able value.
66
66
 
67
67
  Templates also get `admin`, `request`, `user`, `nav` and `admin_page` (also as `page` unless your context sets its own). Build links with `admin.url(request, path)`, which adds the admin's prefix, rather than hard-coding `/admin`.
68
68
 
69
- `admin.page` adds a sidebar entry under `category`; `admin.route` does not, and it may take path parameters. A page path may not start with a registered view identity or `static`: `/task/report` would raise at registration, because `/task/...` belongs to `TaskView`.
69
+ `admin.page` adds a sidebar entry under `category` and cannot take path parameters; `admin.route` adds no entry and may take them, though not as its first segment. A page path may not start with a registered view identity or `static`: `/task/report` would raise at registration, because `/task/...` belongs to `TaskView`. The check runs both ways, so registering a view whose identity a page path already starts with raises too.
70
70
 
71
71
  ## Pages that write
72
72
 
@@ -15,8 +15,8 @@ The built-in templates live under `hxadmin/`. A file at the same path in your di
15
15
  | `hxadmin/layout.html` | Shell: sidebar, top bar, toasts, confirmation dialog |
16
16
  | `hxadmin/dashboard.html` | Dashboard cards |
17
17
  | `hxadmin/list.html`, `hxadmin/list/_toolbar.html`, `hxadmin/list/_table.html`, `hxadmin/list/_pagination.html` | List page, search and filters, table, footer |
18
- | `hxadmin/detail.html`, `hxadmin/detail/_panel.html` | Detail page |
19
- | `hxadmin/form.html`, `hxadmin/form/_fields.html`, `hxadmin/form/_field.html` | Create and edit forms |
18
+ | `hxadmin/detail.html`, `hxadmin/detail/_panel.html`, `hxadmin/detail/_related_plain.html` | Detail page; a to-many tab whose model has no view |
19
+ | `hxadmin/form.html`, `hxadmin/form/_fields.html`, `hxadmin/form/_field.html`, `hxadmin/form/_options.html` | Create and edit forms; relation picker search results |
20
20
  | `hxadmin/page.html` | Base for custom pages (`{% block body %}`) |
21
21
  | `hxadmin/error.html` | Error pages |
22
22
  | `hxadmin/login.html` | Sign-in page rendered by `admin.render_login()`; see [Auth](auth.md#the-sign-in-page) |
@@ -59,7 +59,7 @@ Built-ins refer to each other by their `hxadmin/` names, so the original dashboa
59
59
  | `tooltip`, `kbd` | A hover/focus tooltip; a keyboard-key badge |
60
60
  | `date_input` | A themed date, datetime or time picker submitting ISO values; see [Forms](forms.md#dates-and-times) |
61
61
 
62
- Each component file documents its full signature at the top. Every macro takes `class` (appended to its own classes) and, except `date_input`, `attrs` / `**kwargs` (extra HTML or Alpine attributes, `_` becoming `-`).
62
+ Each component file documents its full signature at the top. Most macros take `class` (appended to their own classes) and `attrs` / `**kwargs` (extra HTML or Alpine attributes, `_` becoming `-`). `tooltip`, `kbd`, `dialog_footer`, `icon` and `date_input` take only `class`; `menu_separator` and `menu_label` take neither.
63
63
 
64
64
  `hxadmin/_macros.html` also renders the admin-specific pieces, which need the request context: `cell(view, field, value, link=True)` formats one value the way lists and the detail page do (`link=False` renders relations as muted text instead of links), and `row_menu`, `filter_button`, `bulk_bar` and `export_menu` render the list's row menu, filter pills, floating selection bar and export menu.
65
65
 
@@ -78,7 +78,7 @@ Row actions live at `/{identity}/{pk}/action/{name}` and bulk actions at `/{iden
78
78
 
79
79
  ## Tokens
80
80
 
81
- Templates use only semantic tokens; raw palette colours (`gray-500`, `blue-600`, ...) exist solely inside `@theme` in `static/src/hxadmin.css`.
81
+ Templates use only semantic tokens, never raw palette colours (`gray-500`, `blue-600`, ...). Their values are set in `@theme` in `static/src/hxadmin.css`.
82
82
 
83
83
  | Group | Tokens |
84
84
  |---|---|
@@ -90,7 +90,7 @@ Templates use only semantic tokens; raw palette colours (`gray-500`, `blue-600`,
90
90
  | Radius | `radius-sm` / `radius-md` / `radius-lg` |
91
91
  | Shadows | `shadow-sm` (cards), `shadow-md` (popovers), `shadow-lg` (dialogs, floating bar) |
92
92
 
93
- Each token is defined once in `@theme` and overridden under `.dark`, so a template never branches on theme itself.
93
+ Each token is defined once in `@theme`, and the colours are overridden under `.dark`, so a template never branches on theme itself.
94
94
 
95
95
  ## Shell
96
96
 
@@ -104,4 +104,4 @@ The top bar holds the breadcrumbs (the parent pages only, since the page title n
104
104
 
105
105
  ## Theme
106
106
 
107
- The theme button in the top bar cycles light → dark → system; its icon shows the current theme and its tooltip names the next. The choice is stored in `localStorage` under `hxadmin-theme` and applied before paint, so there is no flash.
107
+ The theme button in the top bar cycles light → dark → system; its icon shows the current theme and its tooltip names the next. The choice is stored in `localStorage` under `hxadmin-theme` and applied before paint, so there is no flash. Until a choice is made the admin is light; choose system to follow the OS setting.
@@ -45,7 +45,7 @@ Keys are column names; inner keys are the enum's `.value` strings, or `"true"` /
45
45
 
46
46
  ## Detail page
47
47
 
48
- The detail page at `/{prefix}/{identity}/{pk}` shows a back link to the list, the row's `display` as the title with up to two enum badges, and the actions on the right: the row actions as buttons when there are at most two and none needs confirmation (otherwise they move into the `⋯` menu), Edit, and a `⋯` menu holding Delete. The body is a card holding a description list, two columns wide from the `md` breakpoint with each label above its value: the columns first, then the to-one relations in their own group. Long text and JSON span both columns. Values use the same cell formatting as the list; relations link to the related row. When `detail_columns` is empty, foreign-key columns whose relation is also shown are hidden. To-many relations appear as tabs below, each loading its list when first shown.
48
+ The detail page at `/{prefix}/{identity}/{pk}` shows a back link to the list, the row's `display` as the title with up to two enum badges, and the actions on the right: the row actions as buttons when there are at most two and none needs confirmation (otherwise they move into the `⋯` menu), Edit, and a `⋯` menu holding Delete. The body is a card holding a description list, two columns wide from the `md` breakpoint with each label above its value: the columns first, then the to-one relations in their own group. Long text and JSON span both columns. Values use the same cell formatting as the list; relations link to the related row when its model has a view with `can_view` that the current user can access. When `detail_columns` is empty, foreign-key columns whose relation is also shown are hidden. To-many relations appear as tabs below, each loading its list when first shown, through the related view's `get_query`. A relation whose view is not accessible to the current user gets no tab; one whose model has no view shows up to 100 rows as plain text.
49
49
 
50
50
  ## Hooks
51
51
 
@@ -53,7 +53,7 @@ The detail page at `/{prefix}/{identity}/{pk}` shows a back link to the list, th
53
53
  |---|---|
54
54
  | `get_query(request)` | Base `select()` for every list, detail, action and export; scope rows here |
55
55
  | `format_<column>(obj)` | Display override for one column, used in lists, detail and export |
56
- | `display(obj)` | Label of a row (default: `str(obj)` if the model defines `__str__`) |
56
+ | `display(obj)` | Label of a row (default: `str(obj)` if the model defines `__str__`, otherwise the name and primary key, like `Task 3`) |
57
57
  | `on_save(request, session, obj, *, created)` | Runs before commit on create and edit; see [Forms](forms.md#saving) |
58
58
  | `on_delete(request, session, obj)` | Runs before delete |
59
59
  | `is_visible(request)` | Show the view in the sidebar, dashboard and command palette |
@@ -110,7 +110,7 @@ class UserView(ModelView[User]):
110
110
  return request.state.hxadmin_user.is_superuser
111
111
  ```
112
112
 
113
- `is_accessible` is enforced: every route of the view answers 403 for other users, and relations pointing at `User` from other views are locked (see [Lists and filters](lists.md#filters) and [Forms](forms.md)). `is_visible` only hides the view from the sidebar, dashboard and palette; its URLs keep working. Use `is_visible` for views that are reachable through links but too noisy for the sidebar, and `is_accessible` for anything that is a permission.
113
+ `is_accessible` is enforced: every route of the view answers 403 for other users, and relations pointing at `User` from other views are locked (see [Lists and filters](lists.md#filters) and [Forms](forms.md)): detail pages show them as plain text instead of links and leave out their tabs. `is_visible` only hides the view from the sidebar, dashboard and palette; its URLs keep working. Use `is_visible` for views that are reachable through links but too noisy for the sidebar, and `is_accessible` for anything that is a permission.
114
114
 
115
115
  ### Async and relations
116
116
 
@@ -132,3 +132,31 @@ class TaskView(ModelView[Task]):
132
132
  ```
133
133
 
134
134
  `format_` and `display` are plain synchronous methods, so they cannot run queries themselves.
135
+
136
+ ## Helpers
137
+
138
+ A registered view also has methods and attributes that hxadmin's templates use. They are useful in [template overrides](templates.md) and [custom pages](pages.md); `admin.view_for(Model)` returns the view registered for a model, or `None`.
139
+
140
+ | Method | Returns |
141
+ |---|---|
142
+ | `pk_of(obj)` | The row's primary key as it appears in URLs (composite keys `;`-joined) |
143
+ | `pk_clauses(pk)` | `where` clauses matching a URL primary key, for `select(...).where(*view.pk_clauses(pk))` |
144
+ | `cell(obj, name)` | The value shown for a field: `format_<name>(obj)` when defined, else the attribute |
145
+ | `badge_tone(name, raw)` | The `badges` tone of one value (`"neutral"` when none is declared) |
146
+ | `permitted_actions(request, *, bulk)` | The row or bulk actions the current user may run, in declaration order; each has `name`, `label`, `bulk`, `confirm` and `method` |
147
+ | `action_handler(name)` | The bound handler method of an action |
148
+
149
+ These attributes are resolved once at registration and should be treated as read-only:
150
+
151
+ | Attribute | Holds |
152
+ |---|---|
153
+ | `fields` | Every column and relationship of the model, by name |
154
+ | `pk_names` | Names of the primary key columns |
155
+ | `list_fields`, `detail_fields`, `export_fields` | The fields of the list, detail page and export, in order |
156
+ | `writable_fields`, `edit_fields` | The fields of the create form, and of the edit form (without primary keys) |
157
+ | `link_name`, `stretch_name` | The list's primary column (see [Table](lists.md#table)) and the column that takes the remaining width, or `None` |
158
+ | `sort_names` | The columns the list can sort by |
159
+ | `formatted` | Names of the fields with a `format_<name>` method |
160
+ | `filters` | The list's filters, in `list_filters` order |
161
+ | `actions`, `row_actions`, `bulk_actions` | Declared actions: all of them by name, then the row and bulk ones in declaration order |
162
+ | `create_schema`, `edit_schema` | The pydantic models validating the create and edit forms |
@@ -139,8 +139,6 @@ def _column_raw(field_: Field, form: FormData, *, created: bool) -> Any:
139
139
  return value
140
140
  if field_.nullable:
141
141
  return None
142
- if field_.kind in _STRING_KINDS:
143
- return value
144
142
  return _OMITTED if created and not is_required(field_) else value
145
143
 
146
144
 
@@ -169,7 +169,7 @@ def build_router(admin: "HxAdmin") -> APIRouter:
169
169
  collections = [
170
170
  (f, admin.url(request, f"/{view.identity}/_related/{pk}/{f.name}"))
171
171
  for f in view.detail_fields
172
- if isinstance(f, RelationField) and f.multiple
172
+ if isinstance(f, RelationField) and f.multiple and admin.can_reach(request, f.target)
173
173
  ]
174
174
  return {
175
175
  "view": view,
@@ -1,9 +1,9 @@
1
1
  {#-
2
2
  The macro library. Import it with {% import "hxadmin/_macros.html" as m with context %}.
3
3
 
4
- Components live in templates/components/*.html (each documented at the top of its file)
4
+ Components live in hxadmin/components/*.html (each documented at the top of its file)
5
5
  and are re-exported here, so m.button(...) and friends work. Override one by putting a
6
- template of the same name, such as components/button.html, in your templates_dir.
6
+ template of the same name, such as hxadmin/components/button.html, in your templates_dir.
7
7
 
8
8
  icon.html icon
9
9
  button.html button, icon_button, button_classes
@@ -59,7 +59,7 @@
59
59
  {%- set target = admin.view_for(field.target) -%}
60
60
  {%- if not link -%}
61
61
  <span class="text-fg-muted">{{ target.display(value) if target else admin.display(value) }}</span>
62
- {%- elif target and target.can_view -%}
62
+ {%- elif target and target.can_view and target.is_accessible(request) -%}
63
63
  <a class="text-accent hover:underline" href="{{ admin.url(request, '/' ~ target.identity ~ '/' ~ target.pk_of(value)) }}">{{ target.display(value) }}</a>
64
64
  {%- else -%}
65
65
  {{ admin.display(value) }}
@@ -80,13 +80,14 @@
80
80
  {%- endmacro %}
81
81
 
82
82
  {% macro delete_menu_item(view, obj) -%}
83
+ {%- set url = admin.url(request, '/' ~ view.identity ~ '/' ~ view.pk_of(obj) ~ '/delete') -%}
83
84
  {%- set payload = {
84
85
  "title": "Delete " ~ view.name|lower ~ "?",
85
86
  "message": "Delete " ~ view.display(obj) ~ "? This cannot be undone.",
86
87
  "danger": true,
87
- "action": admin.url(request, '/' ~ view.identity ~ '/' ~ view.pk_of(obj) ~ '/delete'),
88
88
  } -%}
89
- {{ menu_item("Delete", icon="trash-2", tone="danger", attrs={"@click": "close(true); $dispatch('confirm', " ~ (payload|tojson|forceescape) ~ ")"}) }}
89
+ {%- set submit = "htmx.ajax('POST', " ~ url|tojson|forceescape ~ ", {swap: 'none'})" -%}
90
+ {{ menu_item("Delete", icon="trash-2", tone="danger", attrs={"@click": "close(true); $dispatch('confirm', Object.assign(" ~ payload|tojson|forceescape ~ ", {submit: () => " ~ submit ~ "}))"}) }}
90
91
  {%- endmacro %}
91
92
 
92
93
  {% macro bulk_bar(view) -%}
@@ -124,6 +124,17 @@ def test_delete_button_dispatches_confirm(factory: AppFactory, make_client: Make
124
124
  assert "@confirm.window" in detail
125
125
 
126
126
 
127
+ def test_delete_confirms_over_htmx_so_a_refusal_is_a_toast(
128
+ factory: AppFactory, make_client: MakeClient
129
+ ) -> None:
130
+ with make_client(build(factory)) as client:
131
+ detail = client.get("/admin/post/1").text
132
+ listing = client.get("/admin/post/").text
133
+ submit = "htmx.ajax(&#39;POST&#39;, &#34;/admin/post/1/delete&#34;, {swap: &#39;none&#39;})"
134
+ assert submit in detail
135
+ assert submit in listing
136
+
137
+
127
138
  def test_delete_returns_to_the_list_as_shown(factory: AppFactory, make_client: MakeClient) -> None:
128
139
  shown = "http://testserver/admin/vote/?f.value.min=2&sort=value&page=1"
129
140
  with make_client(build(factory)) as client:
@@ -200,7 +200,35 @@ def test_related_403_when_target_not_accessible(
200
200
  return False
201
201
 
202
202
  with make_client(app) as client:
203
+ detail = client.get("/admin/group/1").text
203
204
  assert client.get("/admin/group/_related/1/users").status_code == status.HTTP_403_FORBIDDEN
205
+ assert "/admin/group/_related/1/users" not in detail
206
+
207
+
208
+ def test_relation_to_an_inaccessible_view_is_plain_text(
209
+ factory: AppFactory, make_client: Callable[[FastAPI], TestClient]
210
+ ) -> None:
211
+ app = factory.app(seed=seed)
212
+ admin = HxAdmin(app, session=factory.get_session, auth=allow_all)
213
+
214
+ @admin.register
215
+ class PostView(ModelView[Post]):
216
+ model = Post
217
+ list_columns = ("title", "author")
218
+
219
+ @admin.register
220
+ class UserView(ModelView[User]):
221
+ model = User
222
+
223
+ def is_accessible(self, request: Request) -> bool:
224
+ return False
225
+
226
+ with make_client(app) as client:
227
+ detail = client.get("/admin/post/1").text
228
+ listing = client.get("/admin/post/").text
229
+ assert "ada@x.io" in detail
230
+ assert 'href="/admin/user/1"' not in detail
231
+ assert 'href="/admin/user/1"' not in listing
204
232
 
205
233
 
206
234
  def test_related_rejects_non_collection(
@@ -100,7 +100,6 @@ def test_parse_form_normalises_empty_checkbox_and_multi() -> None:
100
100
  raw = parse_form(view.writable_fields, form, created=True)
101
101
  assert raw == {
102
102
  "title": " Hi ",
103
- "body": "",
104
103
  "status": "draft",
105
104
  "published_at": None,
106
105
  "author": "1",
@@ -118,6 +117,13 @@ def test_parse_form_empty_defaulted_column_is_omitted_on_create_and_kept_on_edit
118
117
  assert edited["status"] == ""
119
118
 
120
119
 
120
+ def test_parse_form_empty_defaulted_string_is_omitted_on_create_and_kept_on_edit() -> None:
121
+ fields = (Field("code", "str", required=False),)
122
+ form = FormData([("code", "")])
123
+ assert "code" not in parse_form(fields, form, created=True)
124
+ assert parse_form(fields, form, created=False) == {"code": ""}
125
+
126
+
121
127
  def test_validate_reports_empty_non_nullable_column_as_required() -> None:
122
128
  view = PostView()
123
129
  _, errors = validate(view.edit_schema, {"title": "x", "score": "", "status": "", "author": "1"})
@@ -1,6 +1,8 @@
1
1
  [project]
2
2
  site_name = "hxadmin"
3
3
  site_url = "https://gledi-ai.github.io/hxadmin/"
4
+ repo_url = "https://github.com/gledi-ai/hxadmin"
5
+ repo_name = "gledi-ai/hxadmin"
4
6
  site_description = "Admin interface for FastAPI and SQLAlchemy 2.0+, built with Tailwind CSS and htmx"
5
7
  docs_dir = "docs"
6
8
  site_dir = "site"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes