Skip to content

Core Components

How Admin and SiteRegistry relate

Admin creates no registry of its own — it reads from the module-level site singleton in hyperadmin.core.registry. When you call site.register(MyModel) anywhere in your codebase, that model is automatically available when admin.mount() is called later.

# In myapp/admin.py
from hyperadmin.core.registry import site
site.register(Product)

# In main.py
from hyperadmin import Admin
admin = Admin(app, engine=engine, discover_apps=["myapp"])
admin.mount("/admin")  # picks up Product automatically

Alternatively, use ModelView subclassing — it calls site.register() for you via __init_subclass__:

from hyperadmin.views.dynamic import ModelView

class ProductAdmin(ModelView, model=Product):
    pass  # registered automatically at import time

Admin

hyperadmin.core.app.Admin

The main entry point for HyperAdmin.

Mounts static files, wires the database engine, optionally discovers admin modules, and registers all model routes on the FastAPI application.

All scalar configuration lives in HyperAdminSettings — pass a settings object or let HyperAdmin auto-instantiate one (which reads from environment variables and a .env file).

Example::

from fastapi import FastAPI
from hyperadmin import Admin, HyperAdminSettings

app = FastAPI()
settings = HyperAdminSettings(secret_key="my-secret", theme="dark")
admin = Admin(app, engine=engine, settings=settings)
admin.mount("/admin")
Source code in src/hyperadmin/core/app.py
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
class Admin:
    """The main entry point for HyperAdmin.

    Mounts static files, wires the database engine, optionally discovers admin
    modules, and registers all model routes on the FastAPI application.

    All scalar configuration lives in ``HyperAdminSettings`` — pass a settings
    object or let HyperAdmin auto-instantiate one (which reads from environment
    variables and a ``.env`` file).

    Example::

        from fastapi import FastAPI
        from hyperadmin import Admin, HyperAdminSettings

        app = FastAPI()
        settings = HyperAdminSettings(secret_key="my-secret", theme="dark")
        admin = Admin(app, engine=engine, settings=settings)
        admin.mount("/admin")
    """

    def __init__(
        self,
        app: FastAPI,
        engine: Any = None,
        settings: HyperAdminSettings | None = None,
        auth_backend: Any = None,
        permission_checker: Any = None,
        permission_registry: Any = None,
        storage: Any = None,
        otp_service: Any = None,
        realtime: RealtimeSettings | None = None,
    ) -> None:
        """Initialise HyperAdmin and attach it to a FastAPI application.

        Args:
            app: The FastAPI application instance to attach the admin to.
            engine: An async SQLAlchemy engine. Defaults to the built-in
                ``hyperadmin.db.engine`` if not provided.
            settings: A ``HyperAdminSettings`` instance. When ``None``, one is
                auto-instantiated (reads ``HYPERADMIN_*`` env vars and ``.env``).
            auth_backend: An optional authentication backend implementing the
                ``AuthBackend`` protocol. When ``None``, auth is disabled.
            permission_checker: An optional ``PermissionChecker`` implementation.
            permission_registry: An optional ``PermissionRegistry`` implementation.
            storage: An optional ``FileSystemStorage`` (or compatible) instance
                for file uploads. When ``None``, file upload support is disabled.
            otp_service: An optional MFA OTP service (e.g. ``EmailOTPService``).
                When ``None``, the MFA endpoints (``/mfa/challenge`` etc) are
                NOT registered and ``login_view`` skips the MFA branch — apps
                without MFA are entirely unaffected (C3-A, #487).
            realtime: Opt-in ``RealtimeSettings``. When ``None`` (default),
                no SSE / WebSocket endpoints are registered and the status
                widget is not injected — fully backward compatible. See
                ``docs/specs/realtime-connection-foundation.md``.
        """
        self.settings = settings or HyperAdminSettings()
        self.app = app
        self.router = APIRouter()
        self.engine = engine or default_engine
        self.auth_backend = auth_backend
        self.permission_checker = permission_checker
        self.permission_registry = permission_registry
        self.storage = storage
        self.otp_service = otp_service
        self.realtime = realtime
        self._realtime_registry: ConnectionRegistry | None = (
            ConnectionRegistry() if realtime is not None else None
        )

        self._validate_session_secret()

        template_dirs = self.settings.template_dirs
        template_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "templates")
        self.templates = Jinja2Templates(directory=[*template_dirs, template_dir])
        # Wire jinja2.ext.i18n + per-request gettext callables (C1-C). The
        # callables read translations from a context var populated by
        # LocaleMiddleware; outside a request they pass msgids through.
        from hyperadmin.i18n import install_jinja_i18n

        install_jinja_i18n(self.templates.env)

        static_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "static")
        if os.path.exists(static_dir):
            app.mount("/static", StaticFiles(directory=static_dir), name="static")

        if self.settings.create_tables:

            @app.on_event("startup")
            async def startup_event() -> None:
                await self._create_db_and_tables()

        if self.settings.discover_apps:
            discover_admin_modules(self.settings.discover_apps)

    # ── Convenience properties ─────────────────────────────────────────────

    @property
    def theme(self) -> str:
        """Active theme from settings."""
        return self.settings.theme

    # ── Validation helpers ─────────────────────────────────────────────────

    def _validate_session_secret(self) -> None:
        """Enforce session secret security policy when auth is enabled."""
        if not self.auth_backend:
            return
        if not self.settings.is_default_secret_key:
            return
        if self.settings.debug:
            logger.warning(
                "Using default session secret. Set HYPERADMIN_SECRET_KEY for production."
            )
        else:
            msg = (
                "Auth is enabled but no secret_key is configured. "
                "Set HYPERADMIN_SECRET_KEY (or pass HyperAdminSettings(secret_key=...))."
            )
            raise ValueError(msg)

    # ── Internal helpers ───────────────────────────────────────────────────

    async def _create_db_and_tables(self) -> None:
        """Creates the database and all tables using the configured engine."""
        async with self.engine.begin() as conn:
            await conn.run_sync(SQLModel.metadata.create_all)

    def _register_views(self) -> None:
        """Registers the views from the site registry."""
        from hyperadmin.routing import HyperAdminRouter

        admin_router = HyperAdminRouter(
            engine=self.engine,
            templates=self.templates,
            permission_checker=self.permission_checker if self.auth_backend else None,
            storage=self.storage,
        )
        admin_router.generate_routes()
        routers = admin_router.get_routers()
        for router in routers:
            self.router.include_router(router)

    def _register_auth_routes(self, path: str) -> None:
        """Register login/logout (and MFA) routes when auth is enabled."""
        from starlette.requests import Request

        from hyperadmin.auth.views import login_view, logout_view

        admin_prefix = path.rstrip("/")
        templates = self.templates
        auth_backend = self.auth_backend
        otp_service = self.otp_service

        async def login_get(request: Request):
            return await login_view(request, templates, auth_backend, admin_prefix, otp_service)

        async def login_post(request: Request):
            return await login_view(request, templates, auth_backend, admin_prefix, otp_service)

        async def logout_post(request: Request):
            return await logout_view(request, auth_backend, admin_prefix)

        self.router.add_api_route("/login", login_get, methods=["GET"], name="admin-login")
        self.router.add_api_route("/login", login_post, methods=["POST"], name="admin-login-post")
        self.router.add_api_route("/logout", logout_post, methods=["POST"], name="admin-logout")

        if otp_service is not None:
            self._register_mfa_routes(admin_prefix)

    def _register_mfa_routes(self, admin_prefix: str) -> None:
        """Register the MFA challenge / verify / resend / settings endpoints.

        Only called when ``otp_service`` is configured. Apps without MFA see
        no new routes — ``mfa_enabled=True`` users in such apps will hit the
        normal single-factor path because ``login_view`` skips the MFA branch
        unless an ``otp_service`` is provided.
        """
        from starlette.requests import Request

        from hyperadmin.auth.views import (
            mfa_challenge_view,
            mfa_disable_view,
            mfa_enable_view,
            mfa_resend_view,
            mfa_settings_view,
            mfa_verify_view,
        )

        templates = self.templates
        auth_backend = self.auth_backend
        otp_service = self.otp_service

        async def challenge_get(request: Request):
            return await mfa_challenge_view(request, templates, admin_prefix)

        async def verify_post(request: Request):
            return await mfa_verify_view(
                request, templates, auth_backend, otp_service, admin_prefix
            )

        async def resend_post(request: Request):
            return await mfa_resend_view(
                request, templates, auth_backend, otp_service, admin_prefix
            )

        async def settings_get(request: Request):
            return await mfa_settings_view(request, templates, admin_prefix)

        async def enable_post(request: Request):
            return await mfa_enable_view(
                request, templates, auth_backend, otp_service, admin_prefix
            )

        async def disable_post(request: Request):
            return await mfa_disable_view(
                request, templates, auth_backend, otp_service, admin_prefix
            )

        self.router.add_api_route(
            "/mfa/challenge", challenge_get, methods=["GET"], name="admin-mfa-challenge"
        )
        self.router.add_api_route(
            "/mfa/verify", verify_post, methods=["POST"], name="admin-mfa-verify"
        )
        self.router.add_api_route(
            "/mfa/resend", resend_post, methods=["POST"], name="admin-mfa-resend"
        )
        self.router.add_api_route(
            "/mfa/settings", settings_get, methods=["GET"], name="admin-mfa-settings"
        )
        self.router.add_api_route(
            "/mfa/enable", enable_post, methods=["POST"], name="admin-mfa-enable"
        )
        self.router.add_api_route(
            "/mfa/disable", disable_post, methods=["POST"], name="admin-mfa-disable"
        )

    def _register_realtime_routes(self, path: str) -> None:
        """Register the SSE GET route and WebSocket route under the admin prefix.

        Both endpoints share a single ``ConnectionRegistry`` so the lifespan
        shutdown hook can drain every open connection in one pass.
        """
        if self.realtime is None or self._realtime_registry is None:
            return
        admin_prefix = path.rstrip("/")
        registry = self._realtime_registry
        settings = self.realtime

        sse_handler = make_sse_handler(registry, settings)
        self.router.add_api_route(
            "/realtime/sse",
            sse_handler,
            methods=["GET"],
            name="admin-realtime-sse",
        )
        ws_handler = make_ws_handler(registry, settings, self.auth_backend)
        self.app.router.add_websocket_route(
            f"{admin_prefix}/realtime/ws",
            ws_handler,
            name="admin-realtime-ws",
        )

        @self.app.on_event("shutdown")
        async def _drain_realtime() -> None:
            await registry.drain()

        if settings.enable_test_endpoints:
            from hyperadmin.realtime._debug import (
                make_count_handler,
                make_disconnect_all_handler,
                make_disconnect_transport_handler,
            )

            self.router.add_api_route(
                "/_test/realtime/count",
                make_count_handler(registry),
                methods=["GET"],
                name="admin-realtime-test-count",
            )
            self.router.add_api_route(
                "/_test/realtime/disconnect_all",
                make_disconnect_all_handler(registry),
                methods=["POST"],
                name="admin-realtime-test-disconnect-all",
            )
            self.router.add_api_route(
                "/_test/realtime/disconnect/{transport}",
                make_disconnect_transport_handler(registry),
                methods=["POST"],
                name="admin-realtime-test-disconnect-transport",
            )

    def _register_locale_route(self, path: str) -> None:
        """Register the POST /locale route for the locale switcher."""
        from starlette.requests import Request
        from starlette.responses import Response

        from hyperadmin.views.locale import set_locale_view

        admin_prefix = path.rstrip("/")
        settings = self.settings

        async def locale_post(request: Request) -> Response:
            return await set_locale_view(request, settings, admin_prefix)

        self.router.add_api_route(
            "/locale",
            locale_post,
            methods=["POST"],
            name="admin-locale",
        )

    def _add_auth_middleware(self, path: str) -> None:
        """Add session and authentication middleware."""
        from starlette.middleware.sessions import SessionMiddleware

        from hyperadmin.auth.middleware import AuthenticationMiddleware

        admin_prefix = path.rstrip("/")
        self.app.add_middleware(
            AuthenticationMiddleware,
            auth_backend=self.auth_backend,
            admin_prefix=admin_prefix,
        )
        self.app.add_middleware(
            SessionMiddleware,
            secret_key=self.settings.secret_key,
        )

    def _add_locale_middleware(self) -> None:
        """Add the locale-resolution middleware to the FastAPI app."""
        from hyperadmin.i18n import LocaleMiddleware

        self.app.add_middleware(LocaleMiddleware, settings=self.settings)

    def _mount_upload_storage(self) -> None:
        """Mount the upload storage directory as a static-files endpoint."""
        storage_path = getattr(self.storage, "_path", None)
        if storage_path is None:
            return
        storage_path_str = str(storage_path)
        if os.path.isdir(storage_path_str):
            self.app.mount(
                "/uploads",
                StaticFiles(directory=storage_path_str),
                name="uploads",
            )

    async def _sync_permissions(self) -> None:
        """Sync permissions for all registered models to the database."""
        if not self.permission_registry:
            return

        from hyperadmin.core.registry import site

        models = []
        for model, admin_class in site._registry.items():
            model_name = model.__name__.lower()
            models.append((model_name, admin_class))
        await self.permission_registry.sync_permissions(models)

    def _auto_register_models(self) -> None:
        """Auto-register discovered SQLModel models with smart defaults.

        For each model not already in ``site._registry``, generates
        ``AdminOptions`` with inferred list_display, search_fields,
        and list_filter. Called from ``mount()`` when
        ``settings.auto_discover`` is ``True``.
        """
        from hyperadmin.core.model import ModelAdmin
        from hyperadmin.core.options import AdminOptions
        from hyperadmin.core.registry import site

        discovered = discover_sqlmodel_models()
        for model in discovered:
            if model in site._registry:
                continue
            try:
                options = AdminOptions(
                    list_display=infer_list_display(model),
                    search_fields=infer_search_fields(model),
                    list_filter=infer_list_filter(model),
                )
                admin_cls = type(f"{model.__name__}Admin", (ModelAdmin,), {})
                site.register(model, admin_class=admin_cls, options=options)
            except Exception:
                logger.warning("Failed to auto-register model %s", model.__name__)

    def _register_auth_models(self) -> None:
        """Auto-register User, Group, Permission in the admin site.

        Called from ``mount()`` when ``auth_backend`` is configured.
        Skips silently if a model is already registered.
        Each auth model gets its own admin class to avoid shared
        class-level state on the default ``ModelAdmin``.
        """
        from hyperadmin.auth.models import Group, Permission, User
        from hyperadmin.core.model import ModelAdmin
        from hyperadmin.core.options import AdminOptions
        from hyperadmin.core.registry import site

        if User not in site._registry:
            user_admin = type("UserAdmin", (ModelAdmin,), {})
            site.register(
                User,
                admin_class=user_admin,
                options=AdminOptions(
                    can_delete=False,
                    list_filter=["is_active", "is_superuser"],
                ),
            )
        if Group not in site._registry:
            group_admin = type("GroupAdmin", (ModelAdmin,), {})
            site.register(Group, admin_class=group_admin)
        if Permission not in site._registry:
            perm_admin = type("PermissionAdmin", (ModelAdmin,), {})
            site.register(
                Permission,
                admin_class=perm_admin,
                options=AdminOptions(can_create=False, can_delete=False),
            )

    def mount(self, path: str) -> None:
        """Mounts the admin interface on the FastAPI application."""
        if self.storage:
            self._mount_upload_storage()

        if self.auth_backend:
            self._register_auth_routes(path)
            self._register_auth_models()

        if self.settings.auto_discover:
            self._auto_register_models()

        self._register_locale_route(path)
        self._register_realtime_routes(path)
        self._register_views()
        self.templates.env.globals["admin_prefix"] = path.rstrip("/")
        self.templates.env.globals["auth_enabled"] = self.auth_backend is not None
        self.templates.env.globals["realtime_enabled"] = self.realtime is not None
        self.templates.env.globals["theme"] = self.settings.theme
        self.templates.env.globals["site_title"] = self.settings.site_title
        self.templates.env.globals["site_header"] = self.settings.site_header
        self.templates.env.globals["supported_locales"] = self.settings.supported_locales
        from hyperadmin.i18n import RTL_LOCALES

        self.templates.env.globals["rtl_locales"] = RTL_LOCALES

        if self.auth_backend:
            self.router.on_startup.append(self._sync_permissions)

        self.app.include_router(self.router, prefix=path, tags=["HyperAdmin"])

        # LocaleMiddleware runs whether or not auth is configured. It must be
        # added before the auth middleware so the chain is
        # SessionMiddleware -> AuthenticationMiddleware -> LocaleMiddleware -> routes.
        self._add_locale_middleware()

        if self.auth_backend:
            self._add_auth_middleware(path)

theme property

Active theme from settings.

__init__(app, engine=None, settings=None, auth_backend=None, permission_checker=None, permission_registry=None, storage=None, otp_service=None, realtime=None)

Initialise HyperAdmin and attach it to a FastAPI application.

Parameters:

Name Type Description Default
app FastAPI

The FastAPI application instance to attach the admin to.

required
engine Any

An async SQLAlchemy engine. Defaults to the built-in hyperadmin.db.engine if not provided.

None
settings HyperAdminSettings | None

A HyperAdminSettings instance. When None, one is auto-instantiated (reads HYPERADMIN_* env vars and .env).

None
auth_backend Any

An optional authentication backend implementing the AuthBackend protocol. When None, auth is disabled.

None
permission_checker Any

An optional PermissionChecker implementation.

None
permission_registry Any

An optional PermissionRegistry implementation.

None
storage Any

An optional FileSystemStorage (or compatible) instance for file uploads. When None, file upload support is disabled.

None
otp_service Any

An optional MFA OTP service (e.g. EmailOTPService). When None, the MFA endpoints (/mfa/challenge etc) are NOT registered and login_view skips the MFA branch — apps without MFA are entirely unaffected (C3-A, #487).

None
realtime RealtimeSettings | None

Opt-in RealtimeSettings. When None (default), no SSE / WebSocket endpoints are registered and the status widget is not injected — fully backward compatible. See docs/specs/realtime-connection-foundation.md.

None
Source code in src/hyperadmin/core/app.py
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def __init__(
    self,
    app: FastAPI,
    engine: Any = None,
    settings: HyperAdminSettings | None = None,
    auth_backend: Any = None,
    permission_checker: Any = None,
    permission_registry: Any = None,
    storage: Any = None,
    otp_service: Any = None,
    realtime: RealtimeSettings | None = None,
) -> None:
    """Initialise HyperAdmin and attach it to a FastAPI application.

    Args:
        app: The FastAPI application instance to attach the admin to.
        engine: An async SQLAlchemy engine. Defaults to the built-in
            ``hyperadmin.db.engine`` if not provided.
        settings: A ``HyperAdminSettings`` instance. When ``None``, one is
            auto-instantiated (reads ``HYPERADMIN_*`` env vars and ``.env``).
        auth_backend: An optional authentication backend implementing the
            ``AuthBackend`` protocol. When ``None``, auth is disabled.
        permission_checker: An optional ``PermissionChecker`` implementation.
        permission_registry: An optional ``PermissionRegistry`` implementation.
        storage: An optional ``FileSystemStorage`` (or compatible) instance
            for file uploads. When ``None``, file upload support is disabled.
        otp_service: An optional MFA OTP service (e.g. ``EmailOTPService``).
            When ``None``, the MFA endpoints (``/mfa/challenge`` etc) are
            NOT registered and ``login_view`` skips the MFA branch — apps
            without MFA are entirely unaffected (C3-A, #487).
        realtime: Opt-in ``RealtimeSettings``. When ``None`` (default),
            no SSE / WebSocket endpoints are registered and the status
            widget is not injected — fully backward compatible. See
            ``docs/specs/realtime-connection-foundation.md``.
    """
    self.settings = settings or HyperAdminSettings()
    self.app = app
    self.router = APIRouter()
    self.engine = engine or default_engine
    self.auth_backend = auth_backend
    self.permission_checker = permission_checker
    self.permission_registry = permission_registry
    self.storage = storage
    self.otp_service = otp_service
    self.realtime = realtime
    self._realtime_registry: ConnectionRegistry | None = (
        ConnectionRegistry() if realtime is not None else None
    )

    self._validate_session_secret()

    template_dirs = self.settings.template_dirs
    template_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "templates")
    self.templates = Jinja2Templates(directory=[*template_dirs, template_dir])
    # Wire jinja2.ext.i18n + per-request gettext callables (C1-C). The
    # callables read translations from a context var populated by
    # LocaleMiddleware; outside a request they pass msgids through.
    from hyperadmin.i18n import install_jinja_i18n

    install_jinja_i18n(self.templates.env)

    static_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "static")
    if os.path.exists(static_dir):
        app.mount("/static", StaticFiles(directory=static_dir), name="static")

    if self.settings.create_tables:

        @app.on_event("startup")
        async def startup_event() -> None:
            await self._create_db_and_tables()

    if self.settings.discover_apps:
        discover_admin_modules(self.settings.discover_apps)

mount(path)

Mounts the admin interface on the FastAPI application.

Source code in src/hyperadmin/core/app.py
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
def mount(self, path: str) -> None:
    """Mounts the admin interface on the FastAPI application."""
    if self.storage:
        self._mount_upload_storage()

    if self.auth_backend:
        self._register_auth_routes(path)
        self._register_auth_models()

    if self.settings.auto_discover:
        self._auto_register_models()

    self._register_locale_route(path)
    self._register_realtime_routes(path)
    self._register_views()
    self.templates.env.globals["admin_prefix"] = path.rstrip("/")
    self.templates.env.globals["auth_enabled"] = self.auth_backend is not None
    self.templates.env.globals["realtime_enabled"] = self.realtime is not None
    self.templates.env.globals["theme"] = self.settings.theme
    self.templates.env.globals["site_title"] = self.settings.site_title
    self.templates.env.globals["site_header"] = self.settings.site_header
    self.templates.env.globals["supported_locales"] = self.settings.supported_locales
    from hyperadmin.i18n import RTL_LOCALES

    self.templates.env.globals["rtl_locales"] = RTL_LOCALES

    if self.auth_backend:
        self.router.on_startup.append(self._sync_permissions)

    self.app.include_router(self.router, prefix=path, tags=["HyperAdmin"])

    # LocaleMiddleware runs whether or not auth is configured. It must be
    # added before the auth middleware so the chain is
    # SessionMiddleware -> AuthenticationMiddleware -> LocaleMiddleware -> routes.
    self._add_locale_middleware()

    if self.auth_backend:
        self._add_auth_middleware(path)

SiteRegistry

hyperadmin.core.registry.SiteRegistry

A central, thread-safe registry for managing administrative models.

This registry acts as a single source of truth for all models that HyperAdmin manages. It uses a threading.Lock to ensure that registrations and other operations are atomic, making it safe for use in multi-threaded web applications.

Source code in src/hyperadmin/core/registry.py
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
class SiteRegistry:
    """A central, thread-safe registry for managing administrative models.

    This registry acts as a single source of truth for all models that HyperAdmin
    manages. It uses a `threading.Lock` to ensure that registrations and other
    operations are atomic, making it safe for use in multi-threaded web applications.
    """

    def __init__(self) -> None:
        self._registry: dict[Any, Any] = {}
        self._lock = threading.Lock()

    def register(
        self,
        model: Any,
        admin_class: Any = None,
        options: AdminOptions | None = None,
        app_label: str | None = None,
    ) -> None:
        """
        Registers a model with an optional admin class and admin options.

        This method also discovers the appropriate adapter for the model and attaches
        it to the admin instance.

        Args:
            model: The model class or instance to register.
            admin_class: The admin class to associate with the model. If None,
                ModelAdmin will be used.
            options: The admin options to associate with the model. If None,
                default options will be used.
            app_label: The label of the application that the model belongs to.

        Raises:
            ValueError: If the model is already registered.
            AdapterNotFoundError: If no suitable adapter can be found for the model.
        """
        if admin_class is None:
            from hyperadmin.core.model import ModelAdmin

            admin_class = ModelAdmin

        if options is None:
            options = getattr(admin_class, "options", None) or AdminOptions()
        assert options is not None  # noqa: S101 — narrow the type for downstream

        # Allow ModelAdmin subclasses to declare class-level overrides that
        # we merge into options. Today only ``list_editable`` uses this path;
        # other options remain explicit constructor args. Explicit ``options``
        # always wins over class-level defaults.
        class_list_editable = getattr(admin_class, "list_editable", None)
        if class_list_editable and not options.list_editable:
            options = options.model_copy(update={"list_editable": list(class_list_editable)})

        with self._lock:
            if model in self._registry:
                raise ValueError(f"Model {model} is already registered.")

            admin_class.app_label = app_label
            admin_class.options = options
            admin_class.adapter_class = adapter_registry.find_adapter_for_model(model)
            self._registry[model] = admin_class

    def unregister(self, model: Any) -> None:
        """
        Unregisters a model.

        Args:
            model: The model class or instance to unregister.

        Raises:
            ValueError: If the model is not registered.
        """
        with self._lock:
            if model not in self._registry:
                raise ValueError(f"Model {model} is not registered.")
            del self._registry[model]

    def get_registered_models(self) -> list[Any]:
        """
        Returns a list of all registered models.

        Returns:
            A list of registered models.
        """
        with self._lock:
            return list(self._registry.keys())

get_registered_models()

Returns a list of all registered models.

Returns:

Type Description
list[Any]

A list of registered models.

Source code in src/hyperadmin/core/registry.py
86
87
88
89
90
91
92
93
94
def get_registered_models(self) -> list[Any]:
    """
    Returns a list of all registered models.

    Returns:
        A list of registered models.
    """
    with self._lock:
        return list(self._registry.keys())

register(model, admin_class=None, options=None, app_label=None)

Registers a model with an optional admin class and admin options.

This method also discovers the appropriate adapter for the model and attaches it to the admin instance.

Parameters:

Name Type Description Default
model Any

The model class or instance to register.

required
admin_class Any

The admin class to associate with the model. If None, ModelAdmin will be used.

None
options AdminOptions | None

The admin options to associate with the model. If None, default options will be used.

None
app_label str | None

The label of the application that the model belongs to.

None

Raises:

Type Description
ValueError

If the model is already registered.

AdapterNotFoundError

If no suitable adapter can be found for the model.

Source code in src/hyperadmin/core/registry.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def register(
    self,
    model: Any,
    admin_class: Any = None,
    options: AdminOptions | None = None,
    app_label: str | None = None,
) -> None:
    """
    Registers a model with an optional admin class and admin options.

    This method also discovers the appropriate adapter for the model and attaches
    it to the admin instance.

    Args:
        model: The model class or instance to register.
        admin_class: The admin class to associate with the model. If None,
            ModelAdmin will be used.
        options: The admin options to associate with the model. If None,
            default options will be used.
        app_label: The label of the application that the model belongs to.

    Raises:
        ValueError: If the model is already registered.
        AdapterNotFoundError: If no suitable adapter can be found for the model.
    """
    if admin_class is None:
        from hyperadmin.core.model import ModelAdmin

        admin_class = ModelAdmin

    if options is None:
        options = getattr(admin_class, "options", None) or AdminOptions()
    assert options is not None  # noqa: S101 — narrow the type for downstream

    # Allow ModelAdmin subclasses to declare class-level overrides that
    # we merge into options. Today only ``list_editable`` uses this path;
    # other options remain explicit constructor args. Explicit ``options``
    # always wins over class-level defaults.
    class_list_editable = getattr(admin_class, "list_editable", None)
    if class_list_editable and not options.list_editable:
        options = options.model_copy(update={"list_editable": list(class_list_editable)})

    with self._lock:
        if model in self._registry:
            raise ValueError(f"Model {model} is already registered.")

        admin_class.app_label = app_label
        admin_class.options = options
        admin_class.adapter_class = adapter_registry.find_adapter_for_model(model)
        self._registry[model] = admin_class

unregister(model)

Unregisters a model.

Parameters:

Name Type Description Default
model Any

The model class or instance to unregister.

required

Raises:

Type Description
ValueError

If the model is not registered.

Source code in src/hyperadmin/core/registry.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def unregister(self, model: Any) -> None:
    """
    Unregisters a model.

    Args:
        model: The model class or instance to unregister.

    Raises:
        ValueError: If the model is not registered.
    """
    with self._lock:
        if model not in self._registry:
            raise ValueError(f"Model {model} is not registered.")
        del self._registry[model]

AdminOptions

hyperadmin.core.options.AdminOptions

Bases: BaseModel

Per-model configuration for the HyperAdmin interface.

Pass an instance to site.register() or set it as a class attribute on a ModelView subclass to control which views are generated.

Example
from hyperadmin.core.options import AdminOptions
from hyperadmin.core.registry import site

site.register(Product, options=AdminOptions(can_delete=False))
Source code in src/hyperadmin/core/options.py
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
class AdminOptions(BaseModel):
    """Per-model configuration for the HyperAdmin interface.

    Pass an instance to ``site.register()`` or set it as a class attribute on
    a ``ModelView`` subclass to control which views are generated.

    Example:
        ```python
        from hyperadmin.core.options import AdminOptions
        from hyperadmin.core.registry import site

        site.register(Product, options=AdminOptions(can_delete=False))
        ```
    """

    model_config = ConfigDict(arbitrary_types_allowed=True)

    can_create: bool = True
    """Whether the Create form and POST endpoint are generated."""
    can_edit: bool = True
    """Whether the Edit form and PUT endpoint are generated."""
    can_delete: bool = True
    """Whether the Delete action and DELETE endpoint are generated."""
    can_list: bool = True
    """Whether the List view and GET (collection) endpoint are generated."""
    can_detail: bool = True
    """Whether the Detail view and GET (single item) endpoint are generated."""
    list_display: list[str] | None = None
    """Field names to show in the list view table.

    - ``None`` (default): smart defaults via ``infer_list_display()``.
    - ``[]``: empty — no columns shown (disables feature).
    - ``["id", "name"]``: explicit list used as-is.
    """
    search_fields: list[str] | None = None
    """Field names to include in full-text search.

    - ``None`` (default): smart defaults via ``infer_search_fields()``.
    - ``[]``: search disabled.
    - ``["name", "email"]``: explicit list used as-is.
    """
    list_filter: list[str] | None = None
    """List of field names to show in the filter bar.

    - ``None`` (default): smart defaults via ``infer_list_filter()``.
    - ``[]``: filtering disabled.
    - ``["is_active", "status"]``: explicit list used as-is.
    """
    list_editable: list[str] = Field(default_factory=list)
    """Allow-list of field names that can be inline-edited in the list view.

    Empty by default — feature is opt-in. Fields named here MUST exist on the
    model schema. The primary key (``id``) is never inline-editable, even if
    listed here, and is filtered out at the view layer.
    """
    dependent_fields: dict[str, str] = {}
    """Cascading select configuration: maps child field name → parent field name.

    Example: ``{"city": "country_id"}`` makes the city select reload when country_id changes.
    """
    form_layout: FormLayout = FormLayout.SINGLE
    """Controls the column layout of form fields.

    - ``FormLayout.SINGLE``: One field per row (default).
    - ``FormLayout.TWO_COLUMN``: Fields arranged in a two-column grid.

    Example:
        ```python
        AdminOptions(form_layout=FormLayout.TWO_COLUMN)
        ```
    """
    form_fields: list[str] = []
    """Explicit ordering of fields in create/update forms.

    When non-empty, only these fields are shown, in the specified order.
    When empty, all editable fields are shown in model-definition order.

    Example:
        ```python
        AdminOptions(form_fields=["name", "email", "is_active"])
        ```
    """
    fieldsets: list[FieldsetSpec] = []
    """Groups of fields rendered together under collapsible headings in create/update forms.

    When non-empty, the form renders fields in the order defined by the fieldsets.
    Fields not included in any fieldset are rendered in a default ungrouped section.

    Example:
        ```python
        AdminOptions(fieldsets=[
            FieldsetSpec(name="Basic Info", fields=["name", "email"]),
            FieldsetSpec(name="Advanced", fields=["is_active", "rating"], collapsed=True),
        ])
        ```
    """
    inlines: list[InlineModelSpec] = []
    """Inline related models rendered as sub-forms within create/update views.

    Each ``InlineModelSpec`` defines a related model whose rows can be added,
    edited, and removed directly in the parent form.

    Example:
        ```python
        AdminOptions(inlines=[
            InlineModelSpec(model=OrderItem, fk_field="order_id", extra=3),
        ])
        ```
    """
    object_permission_checker: ObjectPermissionChecker | None = None
    """Per-object permission checker used by the view layer for fine-grained authz.

    When ``None`` (default), no object-level checks are performed and behavior
    matches model-level :class:`PermissionChecker` enforcement only. Provide a
    custom :class:`ObjectPermissionChecker` (or
    :class:`DefaultObjectPermissionChecker` as a permissive baseline) to opt
    into per-object authorization.

    The view layer that consumes this field is wired in a later slot (C2-C);
    declaring it here lets model registrations adopt object-level checks ahead
    of the wiring.
    """
    relation_filters: dict[str, RelationDependency] | None = None
    """Declarative dependent-filtering for FK/M2M autocomplete widgets.

    Keys are child field names; values describe which parent field on the
    same form the child depends on. The widget for each keyed child
    forwards the parent's value via ``hx-include`` so the dropdown narrows
    automatically. See ``docs/specs/htmx-autocomplete.md``.

    Example:
        ```python
        AdminOptions(
            relation_filters={
                "variant_id": RelationDependency(depends_on="supplier_id"),
            }
        )
        ```
    """
    relation_display: dict[str, str | Callable[[Any], str]] | None = None
    """Per-relation option-label rendering.

    Maps a FK/M2M field name to either a Python format string or a callable
    that receives the related instance and returns its display label. Format
    strings are the recommended path; callables are an escape hatch for
    computed properties unreachable via ``getattr``.

    Example:
        ```python
        AdminOptions(relation_display={"supplier_id": "{name} — {city}"})
        ```
    """
    use_autocomplete_widget: bool = True
    """Whether FK/M2M fields render via :class:`AutocompleteWidget`.

    Defaults to ``True``: the new widget is a strict superset of the legacy
    ``<select>`` rendering. Set to ``False`` to opt back into the legacy
    widget on a per-model basis.
    """

    def validate_against_model(self, model: type) -> None:
        """Validate options that reference field names against a concrete model.

        Called by the registry when the options are bound to ``model``. Raises
        :class:`ValueError` if any ``relation_filters[child].depends_on``
        references a field that does not exist on the model.

        Args:
            model: The SQLModel / Pydantic class these options are bound to.

        Raises:
            ValueError: If a referenced field name does not exist on the model.
        """
        if not self.relation_filters:
            return

        field_names = set(getattr(model, "model_fields", {}).keys()) | {
            attr for attr in dir(model) if not attr.startswith("_")
        }
        for child, dep in self.relation_filters.items():
            if dep.depends_on not in field_names:
                raise ValueError(
                    f"relation_filters[{child!r}].depends_on={dep.depends_on!r} "
                    f"not in form fields of {model.__name__}"
                )

can_create = True class-attribute instance-attribute

Whether the Create form and POST endpoint are generated.

can_delete = True class-attribute instance-attribute

Whether the Delete action and DELETE endpoint are generated.

can_detail = True class-attribute instance-attribute

Whether the Detail view and GET (single item) endpoint are generated.

can_edit = True class-attribute instance-attribute

Whether the Edit form and PUT endpoint are generated.

can_list = True class-attribute instance-attribute

Whether the List view and GET (collection) endpoint are generated.

dependent_fields = {} class-attribute instance-attribute

Cascading select configuration: maps child field name → parent field name.

Example: {"city": "country_id"} makes the city select reload when country_id changes.

fieldsets = [] class-attribute instance-attribute

Groups of fields rendered together under collapsible headings in create/update forms.

When non-empty, the form renders fields in the order defined by the fieldsets. Fields not included in any fieldset are rendered in a default ungrouped section.

Example
AdminOptions(fieldsets=[
    FieldsetSpec(name="Basic Info", fields=["name", "email"]),
    FieldsetSpec(name="Advanced", fields=["is_active", "rating"], collapsed=True),
])

form_fields = [] class-attribute instance-attribute

Explicit ordering of fields in create/update forms.

When non-empty, only these fields are shown, in the specified order. When empty, all editable fields are shown in model-definition order.

Example
AdminOptions(form_fields=["name", "email", "is_active"])

form_layout = FormLayout.SINGLE class-attribute instance-attribute

Controls the column layout of form fields.

  • FormLayout.SINGLE: One field per row (default).
  • FormLayout.TWO_COLUMN: Fields arranged in a two-column grid.
Example
AdminOptions(form_layout=FormLayout.TWO_COLUMN)

inlines = [] class-attribute instance-attribute

Inline related models rendered as sub-forms within create/update views.

Each InlineModelSpec defines a related model whose rows can be added, edited, and removed directly in the parent form.

Example
AdminOptions(inlines=[
    InlineModelSpec(model=OrderItem, fk_field="order_id", extra=3),
])

list_display = None class-attribute instance-attribute

Field names to show in the list view table.

  • None (default): smart defaults via infer_list_display().
  • []: empty — no columns shown (disables feature).
  • ["id", "name"]: explicit list used as-is.

list_editable = Field(default_factory=list) class-attribute instance-attribute

Allow-list of field names that can be inline-edited in the list view.

Empty by default — feature is opt-in. Fields named here MUST exist on the model schema. The primary key (id) is never inline-editable, even if listed here, and is filtered out at the view layer.

list_filter = None class-attribute instance-attribute

List of field names to show in the filter bar.

  • None (default): smart defaults via infer_list_filter().
  • []: filtering disabled.
  • ["is_active", "status"]: explicit list used as-is.

object_permission_checker = None class-attribute instance-attribute

Per-object permission checker used by the view layer for fine-grained authz.

When None (default), no object-level checks are performed and behavior matches model-level :class:PermissionChecker enforcement only. Provide a custom :class:ObjectPermissionChecker (or :class:DefaultObjectPermissionChecker as a permissive baseline) to opt into per-object authorization.

The view layer that consumes this field is wired in a later slot (C2-C); declaring it here lets model registrations adopt object-level checks ahead of the wiring.

relation_display = None class-attribute instance-attribute

Per-relation option-label rendering.

Maps a FK/M2M field name to either a Python format string or a callable that receives the related instance and returns its display label. Format strings are the recommended path; callables are an escape hatch for computed properties unreachable via getattr.

Example
AdminOptions(relation_display={"supplier_id": "{name}{city}"})

relation_filters = None class-attribute instance-attribute

Declarative dependent-filtering for FK/M2M autocomplete widgets.

Keys are child field names; values describe which parent field on the same form the child depends on. The widget for each keyed child forwards the parent's value via hx-include so the dropdown narrows automatically. See docs/specs/htmx-autocomplete.md.

Example
AdminOptions(
    relation_filters={
        "variant_id": RelationDependency(depends_on="supplier_id"),
    }
)

search_fields = None class-attribute instance-attribute

Field names to include in full-text search.

  • None (default): smart defaults via infer_search_fields().
  • []: search disabled.
  • ["name", "email"]: explicit list used as-is.

use_autocomplete_widget = True class-attribute instance-attribute

Whether FK/M2M fields render via :class:AutocompleteWidget.

Defaults to True: the new widget is a strict superset of the legacy <select> rendering. Set to False to opt back into the legacy widget on a per-model basis.

validate_against_model(model)

Validate options that reference field names against a concrete model.

Called by the registry when the options are bound to model. Raises :class:ValueError if any relation_filters[child].depends_on references a field that does not exist on the model.

Parameters:

Name Type Description Default
model type

The SQLModel / Pydantic class these options are bound to.

required

Raises:

Type Description
ValueError

If a referenced field name does not exist on the model.

Source code in src/hyperadmin/core/options.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def validate_against_model(self, model: type) -> None:
    """Validate options that reference field names against a concrete model.

    Called by the registry when the options are bound to ``model``. Raises
    :class:`ValueError` if any ``relation_filters[child].depends_on``
    references a field that does not exist on the model.

    Args:
        model: The SQLModel / Pydantic class these options are bound to.

    Raises:
        ValueError: If a referenced field name does not exist on the model.
    """
    if not self.relation_filters:
        return

    field_names = set(getattr(model, "model_fields", {}).keys()) | {
        attr for attr in dir(model) if not attr.startswith("_")
    }
    for child, dep in self.relation_filters.items():
        if dep.depends_on not in field_names:
            raise ValueError(
                f"relation_filters[{child!r}].depends_on={dep.depends_on!r} "
                f"not in form fields of {model.__name__}"
            )