Skip to content

Views

starlette_admin.views

BaseView

Base class for all views

Attributes:

Name Type Description
label str

Label of the view to be displayed.

icon Optional[str]

Icon to be displayed for this model in the admin. Only FontAwesome names are supported.

Source code in starlette_admin/views.py
class BaseView:
    """
    Base class for all views

    Attributes:
        label: Label of the view to be displayed.
        icon: Icon to be displayed for this model in the admin. Only FontAwesome names are supported.
    """

    label: str = ""
    icon: Optional[str] = None

    def title(self, request: Request) -> str:
        """Return the title of the view to be displayed in the browser tab"""
        return self.label

    def is_active(self, request: Request) -> bool:
        """Return true if the current view is active"""
        return False

    def is_accessible(self, request: Request) -> bool:
        """
        Override this method to add permission checks.
        Return True if current user can access this view
        """
        return True

is_accessible(request)

Override this method to add permission checks. Return True if current user can access this view

Source code in starlette_admin/views.py
def is_accessible(self, request: Request) -> bool:
    """
    Override this method to add permission checks.
    Return True if current user can access this view
    """
    return True

is_active(request)

Return true if the current view is active

Source code in starlette_admin/views.py
def is_active(self, request: Request) -> bool:
    """Return true if the current view is active"""
    return False

title(request)

Return the title of the view to be displayed in the browser tab

Source code in starlette_admin/views.py
def title(self, request: Request) -> str:
    """Return the title of the view to be displayed in the browser tab"""
    return self.label

DropDown

Bases: BaseView

Group views inside a dropdown

Example
admin.add_view(
    DropDown(
        "Resources",
        icon="fa fa-list",
        views=[
            ModelView(User),
            Link(label="Home Page", url="/"),
            CustomView(label="Dashboard", path="/dashboard", template_path="dashboard.html"),
        ],
    )
)
Source code in starlette_admin/views.py
class DropDown(BaseView):
    """
    Group views inside a dropdown

    Example:
        ```python
        admin.add_view(
            DropDown(
                "Resources",
                icon="fa fa-list",
                views=[
                    ModelView(User),
                    Link(label="Home Page", url="/"),
                    CustomView(label="Dashboard", path="/dashboard", template_path="dashboard.html"),
                ],
            )
        )
        ```
    """

    def __init__(
        self,
        label: str,
        views: List[Union[Type[BaseView], BaseView]],
        icon: Optional[str] = None,
        always_open: bool = True,
    ) -> None:
        self.label = label
        self.icon = icon
        self.always_open = always_open
        self.views: List[BaseView] = [
            (v if isinstance(v, BaseView) else v()) for v in views
        ]

    def is_active(self, request: Request) -> bool:
        return any(v.is_active(request) for v in self.views)

    def is_accessible(self, request: Request) -> bool:
        return any(v.is_accessible(request) for v in self.views)

Bases: BaseView

Add arbitrary hyperlinks to the menu

Example
admin.add_view(Link(label="Home Page", icon="fa fa-link", url="/"))
Source code in starlette_admin/views.py
class Link(BaseView):
    """
    Add arbitrary hyperlinks to the menu

    Example:
        ```python
        admin.add_view(Link(label="Home Page", icon="fa fa-link", url="/"))
        ```
    """

    def __init__(
        self,
        label: str = "",
        icon: Optional[str] = None,
        url: str = "/",
        target: Optional[str] = "_self",
    ):
        self.label = label
        self.icon = icon
        self.url = url
        self.target = target

CustomView

Bases: BaseView

Add your own views (not tied to any particular model). For example, a custom home page that displays some analytics data.

Attributes:

Name Type Description
path

Route path

template_path

Path to template file

methods

HTTP methods

name

Route name

add_to_menu

Display to menu or not

Example
admin.add_view(CustomView(label="Home", icon="fa fa-home", path="/home", template_path="home.html"))
Source code in starlette_admin/views.py
class CustomView(BaseView):
    """
    Add your own views (not tied to any particular model). For example,
    a custom home page that displays some analytics data.

    Attributes:
        path: Route path
        template_path: Path to template file
        methods: HTTP methods
        name: Route name
        add_to_menu: Display to menu or not

    Example:
        ```python
        admin.add_view(CustomView(label="Home", icon="fa fa-home", path="/home", template_path="home.html"))
        ```
    """

    def __init__(
        self,
        label: str,
        icon: Optional[str] = None,
        path: str = "/",
        template_path: str = "index.html",
        name: Optional[str] = None,
        methods: Optional[List[str]] = None,
        add_to_menu: bool = True,
    ):
        self.label = label
        self.icon = icon
        self.path = path
        self.template_path = template_path
        self.name = name
        self.methods = methods
        self.add_to_menu = add_to_menu

    async def render(self, request: Request, templates: Jinja2Templates) -> Response:
        """Default methods to render view. Override this methods to add your custom logic."""
        return templates.TemplateResponse(
            self.template_path, {"request": request, "title": self.title(request)}
        )

    def is_active(self, request: Request) -> bool:
        return request.scope["path"] == self.path

render(request, templates) async

Default methods to render view. Override this methods to add your custom logic.

Source code in starlette_admin/views.py
async def render(self, request: Request, templates: Jinja2Templates) -> Response:
    """Default methods to render view. Override this methods to add your custom logic."""
    return templates.TemplateResponse(
        self.template_path, {"request": request, "title": self.title(request)}
    )

BaseModelView

Bases: BaseView

Base administrative view. Derive from this class to implement your administrative interface piece.

Attributes:

Name Type Description
identity Optional[str]

Unique identity to identify the model associated to this view. Will be used for URL of the endpoints.

name Optional[str]

Name of the view to be displayed

fields Sequence[BaseField]

List of fields

pk_attr Optional[str]

Primary key field name

form_include_pk bool

Indicates whether the primary key should be included in create and edit forms. Default to False.

exclude_fields_from_list Sequence[str]

List of fields to exclude in List page.

exclude_fields_from_detail Sequence[str]

List of fields to exclude in Detail page.

exclude_fields_from_create Sequence[str]

List of fields to exclude from creation page.

exclude_fields_from_edit Sequence[str]

List of fields to exclude from editing page.

searchable_fields Optional[Sequence[str]]

List of searchable fields.

sortable_fields Optional[Sequence[str]]

List of sortable fields.

export_fields Optional[Sequence[str]]

List of fields to include in exports.

fields_default_sort Optional[Sequence[Union[Tuple[str, bool], str]]]

Initial order (sort) to apply to the table. Should be a sequence of field names or a tuple of (field name, True/False to indicate the sort direction). For example: ["title", ("created_at", False), ("price", True)] will sort by title ascending, created_at ascending and price descending.

export_types Sequence[ExportType]

A list of available export filetypes. Available exports are ['csv', 'excel', 'pdf', 'print']. Only pdf is disabled by default.

column_visibility bool

Enable/Disable column visibility extension

search_builder bool

Enable/Disable search builder extension

page_size int

Default number of items to display in List page pagination. Default value is set to 10.

page_size_options Sequence[int]

Pagination choices displayed in List page. Default value is set to [10, 25, 50, 100]. Use -1to display All

responsive_table bool

Enable/Disable responsive extension

save_state bool

Enable/Disable state saving

datatables_options Dict[str, Any]

Dict of Datatables options. These will overwrite any default options set for the datatable.

list_template str

List view template. Default is list.html.

detail_template str

Details view template. Default is detail.html.

create_template str

Edit view template. Default is create.html.

edit_template str

Edit view template. Default is edit.html.

actions Optional[Sequence[str]]

List of actions

additional_js_links Optional[List[str]]

A list of additional JavaScript files to include.

additional_css_links Optional[List[str]]

A list of additional CSS files to include.

Source code in starlette_admin/views.py
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
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
class BaseModelView(BaseView):
    """
    Base administrative view.
    Derive from this class to implement your administrative interface piece.

    Attributes:
        identity: Unique identity to identify the model associated to this view.
            Will be used for URL of the endpoints.
        name: Name of the view to be displayed
        fields: List of fields
        pk_attr: Primary key field name
        form_include_pk (bool): Indicates whether the primary key should be
            included in create and edit forms. Default to False.
        exclude_fields_from_list: List of fields to exclude in List page.
        exclude_fields_from_detail: List of fields to exclude in Detail page.
        exclude_fields_from_create: List of fields to exclude from creation page.
        exclude_fields_from_edit: List of fields to exclude from editing page.
        searchable_fields: List of searchable fields.
        sortable_fields: List of sortable fields.
        export_fields: List of fields to include in exports.
        fields_default_sort: Initial order (sort) to apply to the table.
            Should be a sequence of field names or a tuple of
            (field name, True/False to indicate the sort direction).
            For example:
            `["title",  ("created_at", False), ("price", True)]` will sort
             by `title` ascending, `created_at` ascending and `price` descending.
        export_types: A list of available export filetypes. Available
            exports are `['csv', 'excel', 'pdf', 'print']`. Only `pdf` is
            disabled by default.
        column_visibility: Enable/Disable
            [column visibility](https://datatables.net/extensions/buttons/built-in#Column-visibility)
            extension
        search_builder: Enable/Disable [search builder](https://datatables.net/extensions/searchbuilder/)
            extension
        page_size: Default number of items to display in List page pagination.
            Default value is set to `10`.
        page_size_options: Pagination choices displayed in List page.
            Default value is set to `[10, 25, 50, 100]`. Use `-1`to display All
        responsive_table: Enable/Disable [responsive](https://datatables.net/extensions/responsive/)
            extension
        save_state: Enable/Disable [state saving](https://datatables.net/examples/basic_init/state_save.html)
        datatables_options: Dict of [Datatables options](https://datatables.net/reference/option/).
            These will overwrite any default options set for the datatable.
        list_template: List view template. Default is `list.html`.
        detail_template: Details view template. Default is `detail.html`.
        create_template: Edit view template. Default is `create.html`.
        edit_template: Edit view template. Default is `edit.html`.
        actions: List of actions
        additional_js_links: A list of additional JavaScript files to include.
        additional_css_links: A list of additional CSS files to include.


    """

    identity: Optional[str] = None
    name: Optional[str] = None
    fields: Sequence[BaseField] = []
    pk_attr: Optional[str] = None
    form_include_pk: bool = False
    exclude_fields_from_list: Sequence[str] = []
    exclude_fields_from_detail: Sequence[str] = []
    exclude_fields_from_create: Sequence[str] = []
    exclude_fields_from_edit: Sequence[str] = []
    searchable_fields: Optional[Sequence[str]] = None
    sortable_fields: Optional[Sequence[str]] = None
    fields_default_sort: Optional[Sequence[Union[Tuple[str, bool], str]]] = None
    export_types: Sequence[ExportType] = [
        ExportType.CSV,
        ExportType.EXCEL,
        ExportType.PRINT,
    ]
    export_fields: Optional[Sequence[str]] = None
    column_visibility: bool = True
    search_builder: bool = True
    page_size: int = 10
    page_size_options: Sequence[int] = [10, 25, 50, 100]
    responsive_table: bool = False
    save_state: bool = True
    datatables_options: ClassVar[Dict[str, Any]] = {}
    list_template: str = "list.html"
    detail_template: str = "detail.html"
    create_template: str = "create.html"
    edit_template: str = "edit.html"
    actions: Optional[Sequence[str]] = None
    row_actions: Optional[Sequence[str]] = None
    additional_js_links: Optional[List[str]] = None
    additional_css_links: Optional[List[str]] = None
    row_actions_display_type: RowActionsDisplayType = RowActionsDisplayType.ICON_LIST

    _find_foreign_model: Callable[[str], "BaseModelView"]

    def __init__(self) -> None:  # noqa: C901
        fringe = list(self.fields)
        all_field_names = []
        while len(fringe) > 0:
            field = fringe.pop(0)
            if not hasattr(field, "_name"):
                field._name = field.name  # type: ignore
            if isinstance(field, CollectionField):
                for f in field.fields:
                    f._name = f"{field._name}.{f.name}"  # type: ignore
                fringe.extend(field.fields)
            name = field._name  # type: ignore
            if name == self.pk_attr and not self.form_include_pk:
                field.exclude_from_create = True
                field.exclude_from_edit = True
            if name in self.exclude_fields_from_list:
                field.exclude_from_list = True
            if name in self.exclude_fields_from_detail:
                field.exclude_from_detail = True
            if name in self.exclude_fields_from_create:
                field.exclude_from_create = True
            if name in self.exclude_fields_from_edit:
                field.exclude_from_edit = True
            if not isinstance(field, CollectionField):
                all_field_names.append(name)
                field.searchable = (self.searchable_fields is None) or (
                    name in self.searchable_fields
                )
                field.orderable = (self.sortable_fields is None) or (
                    name in self.sortable_fields
                )
        if self.searchable_fields is None:
            self.searchable_fields = all_field_names[:]
        if self.sortable_fields is None:
            self.sortable_fields = all_field_names[:]
        if self.export_fields is None:
            self.export_fields = all_field_names[:]
        if self.fields_default_sort is None:
            self.fields_default_sort = [self.pk_attr]  # type: ignore[list-item]

        # Actions
        self._actions: Dict[str, Dict[str, str]] = OrderedDict()
        self._row_actions: Dict[str, Dict[str, str]] = OrderedDict()
        self._actions_handlers: Dict[
            str, Callable[[Request, Sequence[Any]], Awaitable]
        ] = OrderedDict()
        self._row_actions_handlers: Dict[str, Callable[[Request, Any], Awaitable]] = (
            OrderedDict()
        )
        self._init_actions()

    def is_active(self, request: Request) -> bool:
        return request.path_params.get("identity", None) == self.identity

    def _init_actions(self) -> None:
        self._init_batch_actions()
        self._init_row_actions()
        self._validate_actions()

    def _init_batch_actions(self) -> None:
        """
        This method initializes batch and row actions, collects their handlers,
        and validates that all specified actions exist.
        """
        for _method_name, method in inspect.getmembers(
            self, predicate=inspect.ismethod
        ):
            if hasattr(method, "_action"):
                name = method._action.get("name")
                self._actions[name] = method._action
                self._actions_handlers[name] = method

        if self.actions is None:
            self.actions = list(self._actions_handlers.keys())

    def _init_row_actions(self) -> None:
        for _method_name, method in inspect.getmembers(
            self, predicate=inspect.ismethod
        ):
            if hasattr(method, "_row_action"):
                name = method._row_action.get("name")
                self._row_actions[name] = method._row_action
                self._row_actions_handlers[name] = method

        if self.row_actions is None:
            self.row_actions = list(self._row_actions_handlers.keys())

    def _validate_actions(self) -> None:
        for action_name in not_none(self.actions):
            if action_name not in self._actions:
                raise ValueError(f"Unknown action with name `{action_name}`")
        for action_name in not_none(self.row_actions):
            if action_name not in self._row_actions:
                raise ValueError(f"Unknown row action with name `{action_name}`")

    async def is_action_allowed(self, request: Request, name: str) -> bool:
        """
        Verify if action with `name` is allowed.
        Override this method to allow or disallow actions based
        on some condition.

        Args:
            name: Action name
            request: Starlette request
        """
        if name == "delete":
            return self.can_delete(request)
        return True

    async def is_row_action_allowed(self, request: Request, name: str) -> bool:
        """
        Verify if the row action with `name` is allowed.
        Override this method to allow or disallow row actions based
        on some condition.

        Args:
            name: Row action name
            request: Starlette request
        """
        if name == "delete":
            return self.can_delete(request)
        if name == "edit":
            return self.can_edit(request)
        if name == "view":
            return self.can_view_details(request)
        return True

    async def get_all_actions(self, request: Request) -> List[Dict[str, Any]]:
        """Return a list of allowed batch actions"""
        actions = []
        for action_name in not_none(self.actions):
            if await self.is_action_allowed(request, action_name):
                actions.append(self._actions.get(action_name, {}))
        return actions

    async def get_all_row_actions(self, request: Request) -> List[Dict[str, Any]]:
        """Return a list of allowed row actions"""
        row_actions = []
        for row_action_name in not_none(self.row_actions):
            if await self.is_row_action_allowed(request, row_action_name):
                _row_action = self._row_actions.get(row_action_name, {})
                if (
                    request.state.action == RequestAction.LIST
                    and not _row_action.get("exclude_from_list")
                ) or (
                    request.state.action == RequestAction.DETAIL
                    and not _row_action.get("exclude_from_detail")
                ):
                    row_actions.append(_row_action)
        return row_actions

    async def handle_action(
        self, request: Request, pks: List[Any], name: str
    ) -> Union[str, Response]:
        """
        Handle action with `name`.
        Raises:
            ActionFailed: to display meaningfully error
        """
        handler = self._actions_handlers.get(name, None)
        if handler is None:
            raise ActionFailed("Invalid action")
        if not await self.is_action_allowed(request, name):
            raise ActionFailed("Forbidden")
        handler_return = await handler(request, pks)
        custom_response = self._actions[name]["custom_response"]
        if isinstance(handler_return, Response) and not custom_response:
            raise ActionFailed(
                "Set custom_response to true, to be able to return custom response"
            )
        return handler_return

    async def handle_row_action(
        self, request: Request, pk: Any, name: str
    ) -> Union[str, Response]:
        """
        Handle row action with `name`.
        Raises:
            ActionFailed: to display meaningfully error
        """
        handler = self._row_actions_handlers.get(name, None)
        if handler is None:
            raise ActionFailed("Invalid row action")
        if not await self.is_row_action_allowed(request, name):
            raise ActionFailed("Forbidden")
        handler_return = await handler(request, pk)
        custom_response = self._row_actions[name]["custom_response"]
        if isinstance(handler_return, Response) and not custom_response:
            raise ActionFailed(
                "Set custom_response to true, to be able to return custom response"
            )
        return handler_return

    @action(
        name="delete",
        text=_("Delete"),
        confirmation=_("Are you sure you want to delete selected items?"),
        submit_btn_text=_("Yes, delete all"),
        submit_btn_class="btn-danger",
    )
    async def delete_action(self, request: Request, pks: List[Any]) -> str:
        affected_rows = await self.delete(request, pks)
        return ngettext(
            "Item was successfully deleted",
            "%(count)d items were successfully deleted",
            affected_rows or 0,
        ) % {"count": affected_rows}

    @link_row_action(
        name="view",
        text=_("View"),
        icon_class="fa-solid fa-eye",
        exclude_from_detail=True,
    )
    def row_action_1_view(self, request: Request, pk: Any) -> str:
        route_name = request.app.state.ROUTE_NAME
        return str(
            request.url_for(route_name + ":detail", identity=self.identity, pk=pk)
        )

    @link_row_action(
        name="edit",
        text=_("Edit"),
        icon_class="fa-solid fa-edit",
        action_btn_class="btn-primary",
    )
    def row_action_2_edit(self, request: Request, pk: Any) -> str:
        route_name = request.app.state.ROUTE_NAME
        return str(request.url_for(route_name + ":edit", identity=self.identity, pk=pk))

    @row_action(
        name="delete",
        text=_("Delete"),
        confirmation=_("Are you sure you want to delete this item?"),
        icon_class="fa-solid fa-trash",
        submit_btn_text="Yes, delete",
        submit_btn_class="btn-danger",
        action_btn_class="btn-danger",
    )
    async def row_action_3_delete(self, request: Request, pk: Any) -> str:
        await self.delete(request, [pk])
        return gettext("Item was successfully deleted")

    @abstractmethod
    async def find_all(
        self,
        request: Request,
        skip: int = 0,
        limit: int = 100,
        where: Union[Dict[str, Any], str, None] = None,
        order_by: Optional[List[str]] = None,
    ) -> Sequence[Any]:
        """
        Find all items
        Parameters:
            request: The request being processed
            where: Can be dict for complex query
                ```json
                 {"and":[{"id": {"gt": 5}},{"name": {"startsWith": "ban"}}]}
                ```
                or plain text for full search
            skip: should return values start from position skip+1
            limit: number of maximum items to return
            order_by: order data clauses in form `["id asc", "name desc"]`
        """
        raise NotImplementedError()

    @abstractmethod
    async def count(
        self,
        request: Request,
        where: Union[Dict[str, Any], str, None] = None,
    ) -> int:
        """
        Count items
        Parameters:
            request: The request being processed
            where: Can be dict for complex query
                ```json
                 {"and":[{"id": {"gt": 5}},{"name": {"startsWith": "ban"}}]}
                ```
                or plain text for full search
        """
        raise NotImplementedError()

    @abstractmethod
    async def find_by_pk(self, request: Request, pk: Any) -> Any:
        """
        Find one item
        Parameters:
            request: The request being processed
            pk: Primary key
        """
        raise NotImplementedError()

    @abstractmethod
    async def find_by_pks(self, request: Request, pks: List[Any]) -> Sequence[Any]:
        """
        Find many items
        Parameters:
            request: The request being processed
            pks: List of Primary key
        """
        raise NotImplementedError()

    async def before_create(
        self, request: Request, data: Dict[str, Any], obj: Any
    ) -> None:
        """
        This hook is called before a new item is created.

        Args:
            request: The request being processed.
            data: Dict values contained converted form data.
            obj: The object about to be created.
        """

    @abstractmethod
    async def create(self, request: Request, data: Dict) -> Any:
        """
        Create item
        Parameters:
            request: The request being processed
            data: Dict values contained converted form data
        Returns:
            Any: Created Item
        """
        raise NotImplementedError()

    async def after_create(self, request: Request, obj: Any) -> None:
        """
        This hook is called after a new item is successfully created.

        Args:
            request: The request being processed.
            obj: The newly created object.
        """

    async def before_edit(
        self, request: Request, data: Dict[str, Any], obj: Any
    ) -> None:
        """
        This hook is called before an item is edited.

        Args:
            request: The request being processed.
            data: Dict values contained converted form data
            obj: The object about to be edited.
        """

    @abstractmethod
    async def edit(self, request: Request, pk: Any, data: Dict[str, Any]) -> Any:
        """
        Edit item
        Parameters:
            request: The request being processed
            pk: Primary key
            data: Dict values contained converted form data
        Returns:
            Any: Edited Item
        """
        raise NotImplementedError()

    async def after_edit(self, request: Request, obj: Any) -> None:
        """
        This hook is called after an item is successfully edited.

        Args:
            request: The request being processed.
            obj: The edited object.
        """

    async def before_delete(self, request: Request, obj: Any) -> None:
        """
        This hook is called before an item is deleted.

        Args:
            request: The request being processed.
            obj: The object about to be deleted.
        """

    @abstractmethod
    async def delete(self, request: Request, pks: List[Any]) -> Optional[int]:
        """
        Bulk delete items
        Parameters:
            request: The request being processed
            pks: List of primary keys
        """
        raise NotImplementedError()

    async def after_delete(self, request: Request, obj: Any) -> None:
        """
        This hook is called after an item is successfully deleted.

        Args:
            request: The request being processed.
            obj: The deleted object.
        """

    def can_view_details(self, request: Request) -> bool:
        """Permission for viewing full details of Item. Return True by default"""
        return True

    def can_create(self, request: Request) -> bool:
        """Permission for creating new Items. Return True by default"""
        return True

    def can_edit(self, request: Request) -> bool:
        """Permission for editing Items. Return True by default"""
        return True

    def can_delete(self, request: Request) -> bool:
        """Permission for deleting Items. Return True by default"""
        return True

    async def serialize_field_value(
        self, value: Any, field: BaseField, action: RequestAction, request: Request
    ) -> Any:
        """
        Format output value for each field.

        !!! important

            The returned value should be json serializable

        Parameters:
            value: attribute of item returned by `find_all` or `find_by_pk`
            field: Starlette Admin field for this attribute
            action: Specify where the data will be used. Possible values are
                `VIEW` for detail page, `EDIT` for editing page and `API`
                for listing page and select2 data.
            request: The request being processed
        """
        if value is None:
            return await field.serialize_none_value(request, action)
        return await field.serialize_value(request, value, action)

    async def serialize(
        self,
        obj: Any,
        request: Request,
        action: RequestAction,
        include_relationships: bool = True,
        include_select2: bool = False,
    ) -> Dict[str, Any]:
        obj_serialized: Dict[str, Any] = {}
        obj_meta: Dict[str, Any] = {}
        for field in self.get_fields_list(request, action):
            if isinstance(field, RelationField) and include_relationships:
                value = getattr(obj, field.name, None)
                foreign_model = self._find_foreign_model(field.identity)  # type: ignore
                if value is None:
                    obj_serialized[field.name] = None
                elif isinstance(field, HasOne):
                    if action == RequestAction.EDIT:
                        obj_serialized[field.name] = await foreign_model.get_pk_value(
                            request, value
                        )
                    else:
                        obj_serialized[field.name] = await foreign_model.serialize(
                            value, request, action, include_relationships=False
                        )
                else:
                    if action == RequestAction.EDIT:
                        obj_serialized[field.name] = [
                            (await foreign_model.get_pk_value(request, obj))
                            for obj in value
                        ]
                    else:
                        obj_serialized[field.name] = [
                            await foreign_model.serialize(
                                v, request, action, include_relationships=False
                            )
                            for v in value
                        ]
            elif not isinstance(field, RelationField):
                value = await field.parse_obj(request, obj)
                obj_serialized[field.name] = await self.serialize_field_value(
                    value, field, action, request
                )
        if include_select2:
            obj_meta["select2"] = {
                "selection": await self.select2_selection(obj, request),
                "result": await self.select2_result(obj, request),
            }
        obj_meta["repr"] = await self.repr(obj, request)
        pk = await self.get_pk_value(request, obj)
        obj_serialized[not_none(self.pk_attr)] = obj_serialized.get(
            not_none(self.pk_attr),
            pk,  # Make sure the primary key is always available
        )
        route_name = request.app.state.ROUTE_NAME
        obj_meta["detailUrl"] = str(
            request.url_for(route_name + ":detail", identity=self.identity, pk=pk)
        )
        obj_serialized["_meta"] = obj_meta
        return obj_serialized

    async def repr(self, obj: Any, request: Request) -> str:
        """Return a string representation of the given object that can be displayed in the admin interface.

        If the object has a custom representation method `__admin_repr__`, it is used to generate the string. Otherwise,
        the value of the object's primary key attribute is used.

        Args:
            obj: The object to represent.
            request: The request being processed

        Example:
            For example, the following implementation for a `User` model will display
            the user's full name instead of their primary key in the admin interface:

            ```python
            class User:
                id: int
                first_name: str
                last_name: str

                def __admin_repr__(self, request: Request):
                    return f"{self.last_name} {self.first_name}"
            ```
        """
        repr_method = getattr(obj, "__admin_repr__", None)
        if repr_method is None:
            return str(await self.get_pk_value(request, obj))
        if inspect.iscoroutinefunction(repr_method):
            return await repr_method(request)
        return repr_method(request)

    async def select2_result(self, obj: Any, request: Request) -> str:
        """Returns an HTML-formatted string that represents the search results for a Select2 search box.

        By default, this method returns a string that contains all the object's attributes in a list except
        relation and file attributes.

        If the object has a custom representation method `__admin_select2_repr__`, it is used to generate the
        HTML-formatted string.

        !!! note

            The returned value should be valid HTML.

        !!! danger

            Escape your database value to avoid Cross-Site Scripting (XSS) attack.
            You can use Jinja2 Template render with `autoescape=True`.
            For more information [click here](https://owasp.org/www-community/attacks/xss/)

        Parameters:
            obj: The object returned by the `find_all` or `find_by_pk` method.
            request: The request being processed

        Example:
            Here is an example implementation for a `User` model
            that includes the user's name and photo:

            ```python
            class User:
                id: int
                name: str
                photo_url: str

                def __admin_select2_repr__(self, request: Request) -> str:
                    return f'<div><img src="{escape(photo_url)}"><span>{escape(self.name)}</span></div>'
            ```

        """
        template_str = (
            "<span>{%for col in fields %}{%if obj[col]%}<strong>{{col}}:"
            " </strong>{{obj[col]}} {%endif%}{%endfor%}</span>"
        )
        fields = [
            field.name
            for field in self.get_fields_list(request)
            if (
                not isinstance(field, (RelationField, FileField))
                and not field.exclude_from_detail
            )
        ]
        html_repr_method = getattr(
            obj,
            "__admin_select2_repr__",
            lambda request: Template(template_str, autoescape=True).render(
                obj=obj, fields=fields
            ),
        )
        if inspect.iscoroutinefunction(html_repr_method):
            return await html_repr_method(request)
        return html_repr_method(request)

    async def select2_selection(self, obj: Any, request: Request) -> str:
        """
        Returns the HTML representation of an item selected by a user in a Select2 component.
        By default, it simply calls `select2_result()`.

        !!! note

            The returned value should be valid HTML.

        !!! danger

            Escape your database value to avoid Cross-Site Scripting (XSS) attack.
            You can use Jinja2 Template render with `autoescape=True`.
            For more information [click here](https://owasp.org/www-community/attacks/xss/)

        Parameters:
            obj: item returned by `find_all` or `find_by_pk`
            request: The request being processed

        """
        return await self.select2_result(obj, request)

    async def get_pk_value(self, request: Request, obj: Any) -> Any:
        return getattr(obj, not_none(self.pk_attr))

    def _length_menu(self) -> Any:
        return [
            self.page_size_options,
            [(_("All") if i < 0 else i) for i in self.page_size_options],
        ]

    def _search_columns_selector(self) -> List[str]:
        return ["%s:name" % name for name in self.searchable_fields]  # type: ignore

    def _export_columns_selector(self) -> List[str]:
        return ["%s:name" % name for name in self.export_fields]  # type: ignore

    def get_fields_list(
        self,
        request: Request,
        action: RequestAction = RequestAction.LIST,
    ) -> Sequence[BaseField]:
        """Return a list of field instances to display in the specified view action.
        This function excludes fields with corresponding exclude flags, which are
        determined by the `exclude_fields_from_*` attributes.

        Parameters:
             request: The request being processed.
             action: The type of action being performed on the view.
        """
        return extract_fields(self.fields, action)

    def _additional_css_links(
        self, request: Request, action: RequestAction
    ) -> Sequence[str]:
        links = self.additional_css_links or []
        for field in self.get_fields_list(request, action):
            for link in field.additional_css_links(request, action) or []:
                if link not in links:
                    links.append(link)
        return links

    def _additional_js_links(
        self, request: Request, action: RequestAction
    ) -> Sequence[str]:
        links = self.additional_js_links or []
        for field in self.get_fields_list(request, action):
            for link in field.additional_js_links(request, action) or []:
                if link not in links:
                    links.append(link)
        return links

    async def _configs(self, request: Request) -> Dict[str, Any]:
        locale = get_locale()
        return {
            "label": self.label,
            "pageSize": self.page_size,
            "lengthMenu": self._length_menu(),
            "searchColumns": self._search_columns_selector(),
            "exportColumns": self._export_columns_selector(),
            "fieldsDefaultSort": dict(
                (it, False) if isinstance(it, str) else it
                for it in self.fields_default_sort  # type: ignore[union-attr]
            ),
            "exportTypes": self.export_types,
            "columnVisibility": self.column_visibility,
            "searchBuilder": self.search_builder,
            "responsiveTable": self.responsive_table,
            "stateSave": self.save_state,
            "fields": [f.dict() for f in self.get_fields_list(request)],
            "pk": self.pk_attr,
            "locale": locale,
            "apiUrl": request.url_for(
                f"{request.app.state.ROUTE_NAME}:api", identity=self.identity
            ),
            "actionUrl": request.url_for(
                f"{request.app.state.ROUTE_NAME}:action", identity=self.identity
            ),
            "rowActionUrl": request.url_for(
                f"{request.app.state.ROUTE_NAME}:row-action", identity=self.identity
            ),
            "dt_i18n_url": request.url_for(
                f"{request.app.state.ROUTE_NAME}:statics", path=f"i18n/dt/{locale}.json"
            ),
            "datatablesOptions": self.datatables_options,
        }

after_create(request, obj) async

This hook is called after a new item is successfully created.

Parameters:

Name Type Description Default
request Request

The request being processed.

required
obj Any

The newly created object.

required
Source code in starlette_admin/views.py
async def after_create(self, request: Request, obj: Any) -> None:
    """
    This hook is called after a new item is successfully created.

    Args:
        request: The request being processed.
        obj: The newly created object.
    """

after_delete(request, obj) async

This hook is called after an item is successfully deleted.

Parameters:

Name Type Description Default
request Request

The request being processed.

required
obj Any

The deleted object.

required
Source code in starlette_admin/views.py
async def after_delete(self, request: Request, obj: Any) -> None:
    """
    This hook is called after an item is successfully deleted.

    Args:
        request: The request being processed.
        obj: The deleted object.
    """

after_edit(request, obj) async

This hook is called after an item is successfully edited.

Parameters:

Name Type Description Default
request Request

The request being processed.

required
obj Any

The edited object.

required
Source code in starlette_admin/views.py
async def after_edit(self, request: Request, obj: Any) -> None:
    """
    This hook is called after an item is successfully edited.

    Args:
        request: The request being processed.
        obj: The edited object.
    """

before_create(request, data, obj) async

This hook is called before a new item is created.

Parameters:

Name Type Description Default
request Request

The request being processed.

required
data Dict[str, Any]

Dict values contained converted form data.

required
obj Any

The object about to be created.

required
Source code in starlette_admin/views.py
async def before_create(
    self, request: Request, data: Dict[str, Any], obj: Any
) -> None:
    """
    This hook is called before a new item is created.

    Args:
        request: The request being processed.
        data: Dict values contained converted form data.
        obj: The object about to be created.
    """

before_delete(request, obj) async

This hook is called before an item is deleted.

Parameters:

Name Type Description Default
request Request

The request being processed.

required
obj Any

The object about to be deleted.

required
Source code in starlette_admin/views.py
async def before_delete(self, request: Request, obj: Any) -> None:
    """
    This hook is called before an item is deleted.

    Args:
        request: The request being processed.
        obj: The object about to be deleted.
    """

before_edit(request, data, obj) async

This hook is called before an item is edited.

Parameters:

Name Type Description Default
request Request

The request being processed.

required
data Dict[str, Any]

Dict values contained converted form data

required
obj Any

The object about to be edited.

required
Source code in starlette_admin/views.py
async def before_edit(
    self, request: Request, data: Dict[str, Any], obj: Any
) -> None:
    """
    This hook is called before an item is edited.

    Args:
        request: The request being processed.
        data: Dict values contained converted form data
        obj: The object about to be edited.
    """

can_create(request)

Permission for creating new Items. Return True by default

Source code in starlette_admin/views.py
def can_create(self, request: Request) -> bool:
    """Permission for creating new Items. Return True by default"""
    return True

can_delete(request)

Permission for deleting Items. Return True by default

Source code in starlette_admin/views.py
def can_delete(self, request: Request) -> bool:
    """Permission for deleting Items. Return True by default"""
    return True

can_edit(request)

Permission for editing Items. Return True by default

Source code in starlette_admin/views.py
def can_edit(self, request: Request) -> bool:
    """Permission for editing Items. Return True by default"""
    return True

can_view_details(request)

Permission for viewing full details of Item. Return True by default

Source code in starlette_admin/views.py
def can_view_details(self, request: Request) -> bool:
    """Permission for viewing full details of Item. Return True by default"""
    return True

count(request, where=None) abstractmethod async

Count items Parameters: request: The request being processed where: Can be dict for complex query

 {"and":[{"id": {"gt": 5}},{"name": {"startsWith": "ban"}}]}
or plain text for full search

Source code in starlette_admin/views.py
@abstractmethod
async def count(
    self,
    request: Request,
    where: Union[Dict[str, Any], str, None] = None,
) -> int:
    """
    Count items
    Parameters:
        request: The request being processed
        where: Can be dict for complex query
            ```json
             {"and":[{"id": {"gt": 5}},{"name": {"startsWith": "ban"}}]}
            ```
            or plain text for full search
    """
    raise NotImplementedError()

create(request, data) abstractmethod async

Create item Parameters: request: The request being processed data: Dict values contained converted form data Returns: Any: Created Item

Source code in starlette_admin/views.py
@abstractmethod
async def create(self, request: Request, data: Dict) -> Any:
    """
    Create item
    Parameters:
        request: The request being processed
        data: Dict values contained converted form data
    Returns:
        Any: Created Item
    """
    raise NotImplementedError()

delete(request, pks) abstractmethod async

Bulk delete items Parameters: request: The request being processed pks: List of primary keys

Source code in starlette_admin/views.py
@abstractmethod
async def delete(self, request: Request, pks: List[Any]) -> Optional[int]:
    """
    Bulk delete items
    Parameters:
        request: The request being processed
        pks: List of primary keys
    """
    raise NotImplementedError()

edit(request, pk, data) abstractmethod async

Edit item Parameters: request: The request being processed pk: Primary key data: Dict values contained converted form data Returns: Any: Edited Item

Source code in starlette_admin/views.py
@abstractmethod
async def edit(self, request: Request, pk: Any, data: Dict[str, Any]) -> Any:
    """
    Edit item
    Parameters:
        request: The request being processed
        pk: Primary key
        data: Dict values contained converted form data
    Returns:
        Any: Edited Item
    """
    raise NotImplementedError()

find_all(request, skip=0, limit=100, where=None, order_by=None) abstractmethod async

Find all items Parameters: request: The request being processed where: Can be dict for complex query

 {"and":[{"id": {"gt": 5}},{"name": {"startsWith": "ban"}}]}
or plain text for full search skip: should return values start from position skip+1 limit: number of maximum items to return order_by: order data clauses in form ["id asc", "name desc"]

Source code in starlette_admin/views.py
@abstractmethod
async def find_all(
    self,
    request: Request,
    skip: int = 0,
    limit: int = 100,
    where: Union[Dict[str, Any], str, None] = None,
    order_by: Optional[List[str]] = None,
) -> Sequence[Any]:
    """
    Find all items
    Parameters:
        request: The request being processed
        where: Can be dict for complex query
            ```json
             {"and":[{"id": {"gt": 5}},{"name": {"startsWith": "ban"}}]}
            ```
            or plain text for full search
        skip: should return values start from position skip+1
        limit: number of maximum items to return
        order_by: order data clauses in form `["id asc", "name desc"]`
    """
    raise NotImplementedError()

find_by_pk(request, pk) abstractmethod async

Find one item Parameters: request: The request being processed pk: Primary key

Source code in starlette_admin/views.py
@abstractmethod
async def find_by_pk(self, request: Request, pk: Any) -> Any:
    """
    Find one item
    Parameters:
        request: The request being processed
        pk: Primary key
    """
    raise NotImplementedError()

find_by_pks(request, pks) abstractmethod async

Find many items Parameters: request: The request being processed pks: List of Primary key

Source code in starlette_admin/views.py
@abstractmethod
async def find_by_pks(self, request: Request, pks: List[Any]) -> Sequence[Any]:
    """
    Find many items
    Parameters:
        request: The request being processed
        pks: List of Primary key
    """
    raise NotImplementedError()

get_all_actions(request) async

Return a list of allowed batch actions

Source code in starlette_admin/views.py
async def get_all_actions(self, request: Request) -> List[Dict[str, Any]]:
    """Return a list of allowed batch actions"""
    actions = []
    for action_name in not_none(self.actions):
        if await self.is_action_allowed(request, action_name):
            actions.append(self._actions.get(action_name, {}))
    return actions

get_all_row_actions(request) async

Return a list of allowed row actions

Source code in starlette_admin/views.py
async def get_all_row_actions(self, request: Request) -> List[Dict[str, Any]]:
    """Return a list of allowed row actions"""
    row_actions = []
    for row_action_name in not_none(self.row_actions):
        if await self.is_row_action_allowed(request, row_action_name):
            _row_action = self._row_actions.get(row_action_name, {})
            if (
                request.state.action == RequestAction.LIST
                and not _row_action.get("exclude_from_list")
            ) or (
                request.state.action == RequestAction.DETAIL
                and not _row_action.get("exclude_from_detail")
            ):
                row_actions.append(_row_action)
    return row_actions

get_fields_list(request, action=RequestAction.LIST)

Return a list of field instances to display in the specified view action. This function excludes fields with corresponding exclude flags, which are determined by the exclude_fields_from_* attributes.

Parameters:

Name Type Description Default
request Request

The request being processed.

required
action RequestAction

The type of action being performed on the view.

LIST
Source code in starlette_admin/views.py
def get_fields_list(
    self,
    request: Request,
    action: RequestAction = RequestAction.LIST,
) -> Sequence[BaseField]:
    """Return a list of field instances to display in the specified view action.
    This function excludes fields with corresponding exclude flags, which are
    determined by the `exclude_fields_from_*` attributes.

    Parameters:
         request: The request being processed.
         action: The type of action being performed on the view.
    """
    return extract_fields(self.fields, action)

handle_action(request, pks, name) async

Handle action with name. Raises: ActionFailed: to display meaningfully error

Source code in starlette_admin/views.py
async def handle_action(
    self, request: Request, pks: List[Any], name: str
) -> Union[str, Response]:
    """
    Handle action with `name`.
    Raises:
        ActionFailed: to display meaningfully error
    """
    handler = self._actions_handlers.get(name, None)
    if handler is None:
        raise ActionFailed("Invalid action")
    if not await self.is_action_allowed(request, name):
        raise ActionFailed("Forbidden")
    handler_return = await handler(request, pks)
    custom_response = self._actions[name]["custom_response"]
    if isinstance(handler_return, Response) and not custom_response:
        raise ActionFailed(
            "Set custom_response to true, to be able to return custom response"
        )
    return handler_return

handle_row_action(request, pk, name) async

Handle row action with name. Raises: ActionFailed: to display meaningfully error

Source code in starlette_admin/views.py
async def handle_row_action(
    self, request: Request, pk: Any, name: str
) -> Union[str, Response]:
    """
    Handle row action with `name`.
    Raises:
        ActionFailed: to display meaningfully error
    """
    handler = self._row_actions_handlers.get(name, None)
    if handler is None:
        raise ActionFailed("Invalid row action")
    if not await self.is_row_action_allowed(request, name):
        raise ActionFailed("Forbidden")
    handler_return = await handler(request, pk)
    custom_response = self._row_actions[name]["custom_response"]
    if isinstance(handler_return, Response) and not custom_response:
        raise ActionFailed(
            "Set custom_response to true, to be able to return custom response"
        )
    return handler_return

is_action_allowed(request, name) async

Verify if action with name is allowed. Override this method to allow or disallow actions based on some condition.

Parameters:

Name Type Description Default
name str

Action name

required
request Request

Starlette request

required
Source code in starlette_admin/views.py
async def is_action_allowed(self, request: Request, name: str) -> bool:
    """
    Verify if action with `name` is allowed.
    Override this method to allow or disallow actions based
    on some condition.

    Args:
        name: Action name
        request: Starlette request
    """
    if name == "delete":
        return self.can_delete(request)
    return True

is_row_action_allowed(request, name) async

Verify if the row action with name is allowed. Override this method to allow or disallow row actions based on some condition.

Parameters:

Name Type Description Default
name str

Row action name

required
request Request

Starlette request

required
Source code in starlette_admin/views.py
async def is_row_action_allowed(self, request: Request, name: str) -> bool:
    """
    Verify if the row action with `name` is allowed.
    Override this method to allow or disallow row actions based
    on some condition.

    Args:
        name: Row action name
        request: Starlette request
    """
    if name == "delete":
        return self.can_delete(request)
    if name == "edit":
        return self.can_edit(request)
    if name == "view":
        return self.can_view_details(request)
    return True

repr(obj, request) async

Return a string representation of the given object that can be displayed in the admin interface.

If the object has a custom representation method __admin_repr__, it is used to generate the string. Otherwise, the value of the object's primary key attribute is used.

Parameters:

Name Type Description Default
obj Any

The object to represent.

required
request Request

The request being processed

required
Example

For example, the following implementation for a User model will display the user's full name instead of their primary key in the admin interface:

class User:
    id: int
    first_name: str
    last_name: str

    def __admin_repr__(self, request: Request):
        return f"{self.last_name} {self.first_name}"
Source code in starlette_admin/views.py
async def repr(self, obj: Any, request: Request) -> str:
    """Return a string representation of the given object that can be displayed in the admin interface.

    If the object has a custom representation method `__admin_repr__`, it is used to generate the string. Otherwise,
    the value of the object's primary key attribute is used.

    Args:
        obj: The object to represent.
        request: The request being processed

    Example:
        For example, the following implementation for a `User` model will display
        the user's full name instead of their primary key in the admin interface:

        ```python
        class User:
            id: int
            first_name: str
            last_name: str

            def __admin_repr__(self, request: Request):
                return f"{self.last_name} {self.first_name}"
        ```
    """
    repr_method = getattr(obj, "__admin_repr__", None)
    if repr_method is None:
        return str(await self.get_pk_value(request, obj))
    if inspect.iscoroutinefunction(repr_method):
        return await repr_method(request)
    return repr_method(request)

select2_result(obj, request) async

Returns an HTML-formatted string that represents the search results for a Select2 search box.

By default, this method returns a string that contains all the object's attributes in a list except relation and file attributes.

If the object has a custom representation method __admin_select2_repr__, it is used to generate the HTML-formatted string.

Note

The returned value should be valid HTML.

Danger

Escape your database value to avoid Cross-Site Scripting (XSS) attack. You can use Jinja2 Template render with autoescape=True. For more information click here

Parameters:

Name Type Description Default
obj Any

The object returned by the find_all or find_by_pk method.

required
request Request

The request being processed

required
Example

Here is an example implementation for a User model that includes the user's name and photo:

class User:
    id: int
    name: str
    photo_url: str

    def __admin_select2_repr__(self, request: Request) -> str:
        return f'<div><img src="{escape(photo_url)}"><span>{escape(self.name)}</span></div>'
Source code in starlette_admin/views.py
async def select2_result(self, obj: Any, request: Request) -> str:
    """Returns an HTML-formatted string that represents the search results for a Select2 search box.

    By default, this method returns a string that contains all the object's attributes in a list except
    relation and file attributes.

    If the object has a custom representation method `__admin_select2_repr__`, it is used to generate the
    HTML-formatted string.

    !!! note

        The returned value should be valid HTML.

    !!! danger

        Escape your database value to avoid Cross-Site Scripting (XSS) attack.
        You can use Jinja2 Template render with `autoescape=True`.
        For more information [click here](https://owasp.org/www-community/attacks/xss/)

    Parameters:
        obj: The object returned by the `find_all` or `find_by_pk` method.
        request: The request being processed

    Example:
        Here is an example implementation for a `User` model
        that includes the user's name and photo:

        ```python
        class User:
            id: int
            name: str
            photo_url: str

            def __admin_select2_repr__(self, request: Request) -> str:
                return f'<div><img src="{escape(photo_url)}"><span>{escape(self.name)}</span></div>'
        ```

    """
    template_str = (
        "<span>{%for col in fields %}{%if obj[col]%}<strong>{{col}}:"
        " </strong>{{obj[col]}} {%endif%}{%endfor%}</span>"
    )
    fields = [
        field.name
        for field in self.get_fields_list(request)
        if (
            not isinstance(field, (RelationField, FileField))
            and not field.exclude_from_detail
        )
    ]
    html_repr_method = getattr(
        obj,
        "__admin_select2_repr__",
        lambda request: Template(template_str, autoescape=True).render(
            obj=obj, fields=fields
        ),
    )
    if inspect.iscoroutinefunction(html_repr_method):
        return await html_repr_method(request)
    return html_repr_method(request)

select2_selection(obj, request) async

Returns the HTML representation of an item selected by a user in a Select2 component. By default, it simply calls select2_result().

Note

The returned value should be valid HTML.

Danger

Escape your database value to avoid Cross-Site Scripting (XSS) attack. You can use Jinja2 Template render with autoescape=True. For more information click here

Parameters:

Name Type Description Default
obj Any

item returned by find_all or find_by_pk

required
request Request

The request being processed

required
Source code in starlette_admin/views.py
async def select2_selection(self, obj: Any, request: Request) -> str:
    """
    Returns the HTML representation of an item selected by a user in a Select2 component.
    By default, it simply calls `select2_result()`.

    !!! note

        The returned value should be valid HTML.

    !!! danger

        Escape your database value to avoid Cross-Site Scripting (XSS) attack.
        You can use Jinja2 Template render with `autoescape=True`.
        For more information [click here](https://owasp.org/www-community/attacks/xss/)

    Parameters:
        obj: item returned by `find_all` or `find_by_pk`
        request: The request being processed

    """
    return await self.select2_result(obj, request)

serialize_field_value(value, field, action, request) async

Format output value for each field.

Important

The returned value should be json serializable

Parameters:

Name Type Description Default
value Any

attribute of item returned by find_all or find_by_pk

required
field BaseField

Starlette Admin field for this attribute

required
action RequestAction

Specify where the data will be used. Possible values are VIEW for detail page, EDIT for editing page and API for listing page and select2 data.

required
request Request

The request being processed

required
Source code in starlette_admin/views.py
async def serialize_field_value(
    self, value: Any, field: BaseField, action: RequestAction, request: Request
) -> Any:
    """
    Format output value for each field.

    !!! important

        The returned value should be json serializable

    Parameters:
        value: attribute of item returned by `find_all` or `find_by_pk`
        field: Starlette Admin field for this attribute
        action: Specify where the data will be used. Possible values are
            `VIEW` for detail page, `EDIT` for editing page and `API`
            for listing page and select2 data.
        request: The request being processed
    """
    if value is None:
        return await field.serialize_none_value(request, action)
    return await field.serialize_value(request, value, action)