Skip to content

Routing

URL structure

For each registered model (e.g. Product), the following routes are generated under your mount prefix (e.g. /admin):

Method Pattern View Controlled by
GET /admin/product/ List view can_list
GET /admin/product/create Create form can_create
POST /admin/product/ Handle create can_create
GET /admin/product/{id} Detail view can_detail
GET /admin/product/{id}/edit Edit form can_edit
PUT /admin/product/{id} Handle update can_edit
DELETE /admin/product/{id} Delete action can_delete

Routes are only registered for operations enabled by AdminOptions.

HyperAdminRouter

hyperadmin.routing.HyperAdminRouter

Generates and owns all FastAPI routers for HyperAdmin.

Called internally by Admin.mount(). Iterates SiteRegistry and calls create_admin_router for each registered model.

Parameters:

Name Type Description Default
engine Any

The async SQLAlchemy engine passed to every adapter.

required
templates Jinja2Templates

The shared Jinja2Templates instance used across all views.

required
timezone tzinfo | None

The admin's configured display timezone (settings.tzinfo), registered as the ha_display/ha_datetime_input fallback (BYOA SDD A.9). Defaults to UTC.

None
datetime_format str

The admin's configured settings.datetime_format, registered as the ha_display format string (BYOA SDD A.7).

'%Y-%m-%d %H:%M:%S'
session_factory SessionFactory | None

A host-provided session factory forwarded to every adapter alongside (or instead of) engine.

None
debug bool

The admin's settings.debug. List views re-raise database errors instead of rendering the list-error banner (BYOA SDD D.2).

False
route_class type[APIRoute] | None

The admin's HyperAdminRoute (views/route.py), set on every generated router. Defaults to one bound to templates.

None

The timezone and datetime format reach the view layer by living on the shared Jinja environment (as the hyperadmin_timezone / hyperadmin_datetime_format globals register_template_filters sets), not as a constructor argument the view classes read — every view renders through this one environment, so there is nothing else to wire.

Source code in src/hyperadmin/routing.py
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
class HyperAdminRouter:
    """Generates and owns all FastAPI routers for HyperAdmin.

    Called internally by ``Admin.mount()``. Iterates ``SiteRegistry`` and
    calls ``create_admin_router`` for each registered model.

    Args:
        engine: The async SQLAlchemy engine passed to every adapter.
        templates: The shared ``Jinja2Templates`` instance used across all views.
        timezone: The admin's configured display timezone (``settings.tzinfo``),
            registered as the ``ha_display``/``ha_datetime_input`` fallback
            (BYOA SDD A.9). Defaults to UTC.
        datetime_format: The admin's configured ``settings.datetime_format``,
            registered as the ``ha_display`` format string (BYOA SDD A.7).
        session_factory: A host-provided session factory forwarded to every
            adapter alongside (or instead of) ``engine``.
        debug: The admin's ``settings.debug``. List views re-raise database
            errors instead of rendering the list-error banner (BYOA SDD D.2).
        route_class: The admin's ``HyperAdminRoute`` (``views/route.py``), set
            on every generated router. Defaults to one bound to ``templates``.

    The timezone and datetime format reach the view layer by living on the
    shared Jinja environment (as the ``hyperadmin_timezone`` /
    ``hyperadmin_datetime_format`` globals ``register_template_filters``
    sets), not as a constructor argument the view classes read — every view
    renders through this one environment, so there is nothing else to wire.
    """

    def __init__(  # noqa: PLR0913
        self,
        engine: Any,
        templates: Jinja2Templates,
        permission_checker: Any = None,
        storage: Any = None,
        timezone: tzinfo | None = None,
        datetime_format: str = "%Y-%m-%d %H:%M:%S",
        session_factory: "SessionFactory | None" = None,
        *,
        debug: bool = False,
        route_class: type[APIRoute] | None = None,
        realtime_emitter: "RealtimeEmitter | None" = None,
        realtime_settings: "RealtimeSettings | None" = None,
    ):
        self.engine = engine
        self.debug = debug
        # The admin's own HyperAdminRoute (auth bridge, CSRF), or a default one
        # bound to these templates when the router is used on its own.
        self.route_class = route_class or make_admin_route_class(templates)
        self.permission_checker = permission_checker
        self.storage = storage
        self.session_factory = session_factory
        self.realtime_emitter = realtime_emitter
        self.realtime_settings = realtime_settings
        self.notification_models: set[str] = set()
        # Enable global whitespace trimming
        templates.env.trim_blocks = True
        templates.env.lstrip_blocks = True
        register_template_filters(
            templates.env,
            default_timezone=timezone or dt_timezone.utc,
            datetime_format=datetime_format,
        )
        self.templates = templates
        self.routers: list[APIRouter] = []

    def generate_routes(self) -> None:
        """Generates the routes for the registered models."""
        from hyperadmin.core.registry import site

        self.routers = []
        # model -> ModelAdmin instance, shared by every view so cross-model
        # lookups (choices target get_queryset) use the registered admin.
        admin_instances: dict[Any, Any] = {}
        nav_items: list[dict[str, str]] = []
        route_class = self.route_class

        # Add the main admin dashboard route
        dashboard_router = APIRouter(route_class=route_class)
        dashboard_router.add_api_route(
            "/",
            self.get_admin_dashboard_view(),
            methods=["GET"],
            name="admin-dashboard",
        )
        self.routers.append(dashboard_router)

        for model, admin_class in site._registry.items():
            admin_instance = admin_class(model)
            admin_instances[model] = admin_instance
            # Prioritize options set on admin_class, then fall back to defaults
            options = getattr(admin_class, "options", None) or AdminOptions()
            # If admin_class has list_filter set directly (legacy or class-style)
            if hasattr(admin_class, "list_filter") and options.list_filter is None:
                class_filter = getattr(admin_class, "list_filter", None)
                if class_filter:
                    options.list_filter = class_filter

            form_include = _extract_column_names(getattr(admin_class, "form_columns", None), model)
            form_create_exclude = _extract_column_names(
                getattr(admin_class, "form_create_exclude", None), model
            )
            column_list = _extract_column_names(
                getattr(admin_class, "column_list", None) or getattr(admin_class, "list", None),
                model,
            )

            resolved_column_list, resolved_search_fields, options, field_labels = (
                _resolve_smart_defaults(model, options, column_list)
            )

            actions = collect_actions(admin_class)

            router = create_admin_router(
                model=model,
                admin_class=admin_class,
                admin_instance=admin_instance,
                options=options,
                engine=self.engine,
                templates=self.templates,
                form_include=form_include,
                form_create_exclude=form_create_exclude,
                column_list=resolved_column_list,
                permission_checker=self.permission_checker,
                actions=actions,
                search_fields=resolved_search_fields,
                field_labels=field_labels,
                storage=self.storage,
                admin_lookup=admin_instances.get,
                route_class=route_class,
                session_factory=self.session_factory,
                debug=self.debug,
                realtime_emitter=self.realtime_emitter,
                realtime_settings=self.realtime_settings,
            )
            self.routers.append(router)
            if (
                self.realtime_emitter is not None
                and self.realtime_settings is not None
                and notifications_enabled(options, self.realtime_settings)
            ):
                self.notification_models.add(model.__name__.lower())

            model_name = model.__name__
            # Resolve nav label: prefer verbose_name_plural / verbose_name
            # (which may be LazyProxy instances) over the legacy name_plural /
            # name attributes.  Do NOT call str() here — lazy strings must
            # remain lazy so they render in the request locale at template time.
            legacy_name_plural = getattr(admin_class, "name_plural", None)
            if legacy_name_plural:
                nav_name = legacy_name_plural
            elif hasattr(admin_class, "get_verbose_name_plural"):
                nav_name = admin_class.get_verbose_name_plural(model)
            else:
                nav_name = getattr(admin_class, "name", model_name) + "s"
            nav_items.append(
                {
                    "name": nav_name,
                    "url": f"/{model_name.lower()}",
                    "icon": getattr(admin_class, "icon", ""),
                    # The sidebar hides the entry from users without this permission.
                    "permission": f"view_{model_name.lower()}",
                }
            )

        self.templates.env.globals["nav_items"] = nav_items

    def get_admin_dashboard_view(self):
        from hyperadmin.views.dynamic import admin_dashboard

        async def admin_dashboard_view(request: Request):
            return await admin_dashboard(request, self.templates)

        return admin_dashboard_view

    def get_routers(self) -> list[APIRouter]:
        """Returns the list of generated APIRouters."""
        return self.routers

generate_routes()

Generates the routes for the registered models.

Source code in src/hyperadmin/routing.py
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
def generate_routes(self) -> None:
    """Generates the routes for the registered models."""
    from hyperadmin.core.registry import site

    self.routers = []
    # model -> ModelAdmin instance, shared by every view so cross-model
    # lookups (choices target get_queryset) use the registered admin.
    admin_instances: dict[Any, Any] = {}
    nav_items: list[dict[str, str]] = []
    route_class = self.route_class

    # Add the main admin dashboard route
    dashboard_router = APIRouter(route_class=route_class)
    dashboard_router.add_api_route(
        "/",
        self.get_admin_dashboard_view(),
        methods=["GET"],
        name="admin-dashboard",
    )
    self.routers.append(dashboard_router)

    for model, admin_class in site._registry.items():
        admin_instance = admin_class(model)
        admin_instances[model] = admin_instance
        # Prioritize options set on admin_class, then fall back to defaults
        options = getattr(admin_class, "options", None) or AdminOptions()
        # If admin_class has list_filter set directly (legacy or class-style)
        if hasattr(admin_class, "list_filter") and options.list_filter is None:
            class_filter = getattr(admin_class, "list_filter", None)
            if class_filter:
                options.list_filter = class_filter

        form_include = _extract_column_names(getattr(admin_class, "form_columns", None), model)
        form_create_exclude = _extract_column_names(
            getattr(admin_class, "form_create_exclude", None), model
        )
        column_list = _extract_column_names(
            getattr(admin_class, "column_list", None) or getattr(admin_class, "list", None),
            model,
        )

        resolved_column_list, resolved_search_fields, options, field_labels = (
            _resolve_smart_defaults(model, options, column_list)
        )

        actions = collect_actions(admin_class)

        router = create_admin_router(
            model=model,
            admin_class=admin_class,
            admin_instance=admin_instance,
            options=options,
            engine=self.engine,
            templates=self.templates,
            form_include=form_include,
            form_create_exclude=form_create_exclude,
            column_list=resolved_column_list,
            permission_checker=self.permission_checker,
            actions=actions,
            search_fields=resolved_search_fields,
            field_labels=field_labels,
            storage=self.storage,
            admin_lookup=admin_instances.get,
            route_class=route_class,
            session_factory=self.session_factory,
            debug=self.debug,
            realtime_emitter=self.realtime_emitter,
            realtime_settings=self.realtime_settings,
        )
        self.routers.append(router)
        if (
            self.realtime_emitter is not None
            and self.realtime_settings is not None
            and notifications_enabled(options, self.realtime_settings)
        ):
            self.notification_models.add(model.__name__.lower())

        model_name = model.__name__
        # Resolve nav label: prefer verbose_name_plural / verbose_name
        # (which may be LazyProxy instances) over the legacy name_plural /
        # name attributes.  Do NOT call str() here — lazy strings must
        # remain lazy so they render in the request locale at template time.
        legacy_name_plural = getattr(admin_class, "name_plural", None)
        if legacy_name_plural:
            nav_name = legacy_name_plural
        elif hasattr(admin_class, "get_verbose_name_plural"):
            nav_name = admin_class.get_verbose_name_plural(model)
        else:
            nav_name = getattr(admin_class, "name", model_name) + "s"
        nav_items.append(
            {
                "name": nav_name,
                "url": f"/{model_name.lower()}",
                "icon": getattr(admin_class, "icon", ""),
                # The sidebar hides the entry from users without this permission.
                "permission": f"view_{model_name.lower()}",
            }
        )

    self.templates.env.globals["nav_items"] = nav_items

get_routers()

Returns the list of generated APIRouters.

Source code in src/hyperadmin/routing.py
594
595
596
def get_routers(self) -> list[APIRouter]:
    """Returns the list of generated APIRouters."""
    return self.routers