Skip to content

components

django_spire.core.components

__all__ = ['BaseConfirmationComponent', 'BaseFormComponent', 'BaseModelActionConfirmationComponent', 'BaseModelDeleteConfirmationComponent', 'BaseScrollComponent', 'ConfirmationRefusedError', 'FormComponent', 'ModelCrudScrollComponent', 'ModelDeleteConfirmationComponent', 'ModelFormComponent', 'ModelSetDeletedConfirmationComponent', 'QuerySetScrollComponent', 'SearchAndSortScrollMixin', 'Tab', 'TabsComponent'] module-attribute

BaseConfirmationComponent

Bases: Component, ABC

Asks the user to confirm one action.

Subclasses perform the action in on_confirm(). The prompt is worded when the component is built, with title, message and confirm_label; one left unset keeps the template's own wording::

ArchiveConfirmationComponent(title='Archive this report?', confirm_label='Archive')

A subclass that needs markup, such as an icon, extends the template's confirmation_title, confirmation_message and confirmation_button blocks. confirmation_button holds the whole confirm button.

The component does not know what it is shown in, so it closes nothing. Whoever shows it listens for confirmed, which carries what on_confirm() returned, and for cancelled, and puts it away. Cancelling does nothing on the server, so the template raises cancelled in the browser.

What the user sees once the action is done, such as a toast, is the template's: its on_confirmed block runs in the browser after a successful confirm(), with what on_confirm() returned as result, as a form's glue_form_on_saved block does after a save.

An action that cannot be performed, because its row changed while the prompt was open say, raises ConfirmationRefusedError: confirmed is not fired, and the prompt stays open and shows the error's message.

confirm_access is the access the user needs in order to confirm.

template = 'django_spire/component/confirmation/confirmation.html' class-attribute instance-attribute

confirm_access = Glue.Access.VIEW class-attribute

title = Glue.ComponentParameter(None) class-attribute instance-attribute

message = Glue.ComponentParameter(None) class-attribute instance-attribute

confirm_label = Glue.ComponentParameter(None) class-attribute instance-attribute

cancelled = Glue.event() class-attribute instance-attribute

confirmed = Glue.event() class-attribute instance-attribute

on_confirm abstractmethod

Perform the confirmed action and return the detail of confirmed, or raise ConfirmationRefusedError to leave the prompt open with its message.

Source code in django_spire/core/components/confirmation/base_component.py
@abstractmethod
def on_confirm(self) -> dict[str, Any]:
    """
    Perform the confirmed action and return the detail of ``confirmed``, or
    raise ``ConfirmationRefusedError`` to leave the prompt open with its message.
    """

confirm

Source code in django_spire/core/components/confirmation/base_component.py
@Glue.attr(required_access=lambda component: component.confirm_access, skip_rerender=True)
def confirm(self) -> Glue.Response:
    try:
        detail = self.on_confirm()
    except ConfirmationRefusedError as error:
        return Glue.Response(messages=[Glue.Response.Message.error(str(error))])

    self.confirmed(**detail)

    return Glue.Response(result={'confirmed': True, **detail})

BaseModelActionConfirmationComponent

Bases: BaseConfirmationComponent, ABC

A :class:BaseConfirmationComponent for one action on one model row.

Built with the row, as instance=, it works for any model. Confirming performs the action with perform_action(), which a subclass writes, and fires confirmed with the row's pk.

model_name property

instance

Source code in django_spire/core/components/confirmation/model/action_component.py
@Glue.ComponentParameter
def instance(self, model: type[Model], pk: int) -> Model:
    return model._default_manager.get(pk=pk)

get_permission_model

Return the row's model, whose permissions Glue.ModelAccessMixin reads.

Source code in django_spire/core/components/confirmation/model/action_component.py
def get_permission_model(self) -> type[Model]:
    """Return the row's model, whose permissions ``Glue.ModelAccessMixin`` reads."""
    return self.instance._meta.model

perform_action abstractmethod

Perform the confirmed action on self.instance.

Source code in django_spire/core/components/confirmation/model/action_component.py
@abstractmethod
def perform_action(self) -> None:
    """Perform the confirmed action on ``self.instance``."""

on_confirm

Source code in django_spire/core/components/confirmation/model/action_component.py
def on_confirm(self) -> dict[str, Any]:
    pk = self.instance.pk

    self.perform_action()

    return {'pk': pk}

BaseModelDeleteConfirmationComponent

Bases: BaseModelActionConfirmationComponent, ABC

A :class:BaseModelActionConfirmationComponent worded and guarded as a delete: confirming needs DELETE access, and title, message and confirm_label name the row and its model when left unset.

A subclass deletes the row in perform_action().

template = 'django_spire/component/confirmation/model_delete_confirmation.html' class-attribute instance-attribute

confirm_access = Glue.Access.DELETE class-attribute instance-attribute

ConfirmationRefusedError

Bases: DjangoSpireError

The confirmed action was not performed; its message tells the user why.

ModelDeleteConfirmationComponent

Bases: BaseModelDeleteConfirmationComponent

Deletes the row from the database, with the model's delete().

perform_action

Source code in django_spire/core/components/confirmation/model/delete_component.py
def perform_action(self) -> None:
    self.instance.delete()

ModelSetDeletedConfirmationComponent

Bases: BaseModelDeleteConfirmationComponent

Soft-deletes the row, with the set_deleted() of Spire's history mixin.

perform_action

Source code in django_spire/core/components/confirmation/model/delete_component.py
def perform_action(self) -> None:
    self.instance.set_deleted()

BaseFormComponent

Bases: Component, ABC

Shows one form. The form class and the template are set on a subclass, as form_class and template, or passed when the component is built::

ModelFormComponent(form_class=TaskForm, template='task/form.html')

Either way the form class must be importable from its module, because the component is rebuilt on each request from its signed path.

glue_form_path() is the dot path to the form, read by the template and its partials as component.glue_form_path. glue_form_object_name is the name the form's Alpine scope gives it, so a template can call it account_form instead of glue_form. Whether the component is shown in a modal, inline or on a page is the choice of whoever shows it.

Source code in django_spire/core/components/form/base_component.py
def __init__(
    self,
    *,
    form_class: type[BaseForm] | None = None,
    template: str | None = None,
    **kwargs: Any,
) -> None:
    if form_class is not None:
        kwargs['form_path'] = f'{form_class.__module__}:{form_class.__qualname__}'

    if template is not None:
        kwargs['template_name'] = template

    if kwargs.get('template_name') is not None:
        self.template = kwargs['template_name']

    super().__init__(**kwargs)

    if self.form_path is not None:
        module_name, _, qualified_name = self.form_path.partition(':')

        try:
            form_class = import_module(module_name)

            for part in qualified_name.split('.'):
                form_class = getattr(form_class, part)
        except (ImportError, AttributeError) as error:
            message = (
                f'{type(self).__name__} cannot import its form from {self.form_path!r}: '
                'the form class must be defined at module level.'
            )
            raise ImproperlyConfigured(message) from error

        self.form_class = form_class

    self.validate_form_class(self.form_class)

form_base = BaseForm class-attribute

form_class = None class-attribute

glue_form_object_name = 'glue_form' class-attribute

form_path = Glue.ComponentParameter(None) class-attribute instance-attribute

template_name = Glue.ComponentParameter(None) class-attribute instance-attribute

template = kwargs['template_name'] instance-attribute

__init_subclass__

Source code in django_spire/core/components/form/base_component.py
def __init_subclass__(cls, **kwargs: Any) -> None:
    super().__init_subclass__(**kwargs)

    if cls.form_class is not None:
        cls.validate_form_class(cls.form_class)

validate_form_class classmethod

Source code in django_spire/core/components/form/base_component.py
@classmethod
def validate_form_class(cls, form_class: Any) -> None:
    if not isinstance(form_class, type) or not issubclass(form_class, cls.form_base):
        message = f'{cls.__name__} needs form_class to be a {cls.form_base.__name__} class.'
        raise TypeError(message)

glue_form_path abstractmethod

Return the dot path, from the template, to the form this component shows.

Source code in django_spire/core/components/form/base_component.py
@abstractmethod
def glue_form_path(self) -> str:
    """Return the dot path, from the template, to the form this component shows."""

FormComponent

Bases: BaseFormComponent

A :class:BaseFormComponent over a plain form, exposed as the form child. Override get_form() when the form needs constructor arguments from the component's parameters.

Source code in django_spire/core/components/form/base_component.py
def __init__(
    self,
    *,
    form_class: type[BaseForm] | None = None,
    template: str | None = None,
    **kwargs: Any,
) -> None:
    if form_class is not None:
        kwargs['form_path'] = f'{form_class.__module__}:{form_class.__qualname__}'

    if template is not None:
        kwargs['template_name'] = template

    if kwargs.get('template_name') is not None:
        self.template = kwargs['template_name']

    super().__init__(**kwargs)

    if self.form_path is not None:
        module_name, _, qualified_name = self.form_path.partition(':')

        try:
            form_class = import_module(module_name)

            for part in qualified_name.split('.'):
                form_class = getattr(form_class, part)
        except (ImportError, AttributeError) as error:
            message = (
                f'{type(self).__name__} cannot import its form from {self.form_path!r}: '
                'the form class must be defined at module level.'
            )
            raise ImproperlyConfigured(message) from error

        self.form_class = form_class

    self.validate_form_class(self.form_class)

form

Source code in django_spire/core/components/form/form_component.py
@Glue.child
def form(self) -> Glue.Form:
    return Glue.form(target=self.get_form(), access=self.access)

get_form

Source code in django_spire/core/components/form/form_component.py
def get_form(self) -> BaseForm:
    return self.form_class()

glue_form_path

Source code in django_spire/core/components/form/form_component.py
def glue_form_path(self) -> str:
    return 'component.form'

ModelFormComponent

Bases: BaseFormComponent

A :class:BaseFormComponent over a ModelForm, whose model is the form's own. model_pk=None opens the create flow and a value opens the edit flow. The row is exposed as the model child, a Glue.model, so the form lives at component.model.form.

The data for the child comes from two overridable hooks: get_model() picks the instance (blank or fetched by model_pk by default), and get_fields() names the exposed fields (the form's own fields unless fields is set), so scoping and create defaults stay subclass logic. A relation field's choices are the form's own: its __init__ narrows a field's queryset, which the form child reads, with the row as self.instance.

pk is the deprecated name of model_pk, both as a parameter and as an attribute.

Source code in django_spire/core/components/form/model_component.py
def __init__(self, **parameters: Any) -> None:
    if 'pk' in parameters:
        if 'model_pk' in parameters:
            message = f'{type(self).__name__} takes model_pk or the deprecated pk, not both.'
            raise GlueComponentParameterError(message)

        warnings.warn(
            'The pk parameter of ModelFormComponent is deprecated; pass model_pk instead.',
            DeprecationWarning,
            stacklevel=2,
        )
        parameters['model_pk'] = parameters.pop('pk')

    super().__init__(**parameters)

form_base = ModelForm class-attribute instance-attribute

form_class = None class-attribute

fields = None class-attribute

model_pk = Glue.ComponentParameter(None) class-attribute instance-attribute

pk property

model

Source code in django_spire/core/components/form/model_component.py
@Glue.child
def model(self) -> Glue.Model:
    target = self.get_model()
    initial = self.get_initial()

    if initial:
        form = self.form_class(instance=target, initial=initial)
        form.initial = dict(initial)
    else:
        form = self.form_class

    return Glue.model(
        target=target,
        access=self.access,
        fields=self.get_fields(),
        form=form,
    )

get_initial

Source code in django_spire/core/components/form/model_component.py
def get_initial(self) -> dict[str, Any]:
    return {}

get_fields

Source code in django_spire/core/components/form/model_component.py
def get_fields(self) -> Sequence[str]:
    if self.fields is None:
        model_field_names = {
            field.name for field in self.form_class._meta.model._meta.get_fields()
        }
        return tuple(name for name in self.form_class.base_fields if name in model_field_names)
    return self.fields

get_model

Source code in django_spire/core/components/form/model_component.py
def get_model(self) -> Model:
    model_class = self.form_class._meta.model
    if self.model_pk is None:
        return model_class()

    try:
        return model_class.objects.get(pk=self.model_pk)
    except model_class.DoesNotExist as error:
        raise GlueModelInstanceNotFoundError(model_class._meta.label, self.model_pk) from error

get_permission_model

Return the form's model, whose permissions Glue.ModelAccessMixin reads.

Source code in django_spire/core/components/form/model_component.py
def get_permission_model(self) -> type[Model]:
    """Return the form's model, whose permissions ``Glue.ModelAccessMixin`` reads."""
    return self.form_class._meta.model

get_required_access

ADD to create a row and CHANGE to edit one, for Glue.ModelAccessRequiredMixin.

Source code in django_spire/core/components/form/model_component.py
def get_required_access(self) -> Glue.Access:
    """``ADD`` to create a row and ``CHANGE`` to edit one, for ``Glue.ModelAccessRequiredMixin``."""
    return Glue.Access.ADD if self.model_pk is None else Glue.Access.CHANGE

glue_form_path

Source code in django_spire/core/components/form/model_component.py
def glue_form_path(self) -> str:
    return 'component.model.form'

BaseScrollComponent

Bases: Component, ABC

An infinite list of any kind of item.

Subclasses supply the items through get_items(), get_item() and get_item_key(); this base owns paging and every client behaviour. The server keeps no position: the client sends the number of items it holds, and a render always shows the first batch.

item_template is the markup for one item. Each item is rendered on the server, so the template must extend the scroll's item/item.html or item/table_item.html.

A callable that changes an item fires item_added, item_changed or item_removed with key=, and the list updates that one row.

Served by as_view(), the list fills spire's full page.

template = 'django_spire/component/scroll/scroll.html' class-attribute instance-attribute

view_template = 'django_spire/component/page/full_page.html' class-attribute instance-attribute

item_template = None class-attribute

batch_size = 25 class-attribute

item_added = Glue.event() class-attribute instance-attribute

item_changed = Glue.event() class-attribute instance-attribute

item_removed = Glue.event() class-attribute instance-attribute

renders_items_on_server property

first_batch cached property

get_items abstractmethod

Return up to limit items starting at offset, in an order that is the same on every call.

Source code in django_spire/core/components/scroll/base_component.py
@abstractmethod
def get_items(self, offset: int, limit: int) -> list[Any]:
    """
    Return up to ``limit`` items starting at ``offset``, in an order that
    is the same on every call.
    """

get_item abstractmethod

Return the item with this key, or None when it no longer belongs in the list.

Source code in django_spire/core/components/scroll/base_component.py
@abstractmethod
def get_item(self, key: Any) -> Any | None:
    """Return the item with this key, or ``None`` when it no longer belongs in the list."""

get_item_key abstractmethod

Return the value that identifies item among all items.

Source code in django_spire/core/components/scroll/base_component.py
@abstractmethod
def get_item_key(self, item: Any) -> Any:
    """Return the value that identifies ``item`` among all items."""

introduce

Check, once per class, that its templates extend the scroll's own.

Source code in django_spire/core/components/scroll/base_component.py
def introduce(self, request: HttpRequest) -> None:
    """Check, once per class, that its templates extend the scroll's own."""
    scroll_class = type(self)

    if scroll_class not in self._validated_classes:
        self._validate_templates()
        self._validated_classes.add(scroll_class)

    super().introduce(request)

load_items

Source code in django_spire/core/components/scroll/base_component.py
@Glue.attr(skip_rerender=True)
def load_items(self, request: HttpRequest, offset: int) -> GlueResponse:
    self._refuse_unless_rendered_on_server()
    self._validate_offset(offset)

    return GlueTemplateResponse(
        request,
        BATCH_TEMPLATE,
        {
            'batch': self._get_batch(offset),
            'component': self,
        },
    )

load_item

Source code in django_spire/core/components/scroll/base_component.py
@Glue.attr(skip_rerender=True)
def load_item(self, request: HttpRequest, key: int | str) -> GlueResponse | None:
    self._refuse_unless_rendered_on_server()

    item = self.get_item(key)

    if item is None:
        return None

    return GlueTemplateResponse(
        request,
        self.item_template,
        {
            'item': item,
            'item_key': self.get_item_key(item),
            'component': self,
        },
    )

ModelCrudScrollComponent

Bases: QuerySetScrollComponent, ABC

A :class:QuerySetScrollComponent with ready-made actions on its rows. The template's createItem(), editItem(item) and deleteItem(item) perform them, and each takes the item or its key.

item_form_options says how a row is created and edited: a ModelCrudScrollComponent.FormOptions shows a form component in a modal, and a ModelCrudScrollComponent.PageFormOptions sends the user to a page. Left as None, the list has no create or edit.

item_delete_options says how a row is deleted: a ModelCrudScrollComponent.DeleteOptions shows a confirmation component in a modal, and a ModelCrudScrollComponent.PageDeleteOptions sends the user to a page. The default is a confirmation that soft-deletes the row with set_deleted(). Left as None, the list has no delete.

Only rows in get_queryset() can be edited or deleted. The browser fetches the form and the confirmation with load_item_form() and load_item_delete_confirmation(), which check the user's access and that the row is in the list. Customise an action through the two settings and get_queryset(), which keep those checks, and not by overriding the callables.

DeleteOptions = delete_options.DeleteOptions class-attribute instance-attribute

PageDeleteOptions = delete_options.PageDeleteOptions class-attribute instance-attribute

FormOptions = form_options.FormOptions class-attribute instance-attribute

PageFormOptions = form_options.PageFormOptions class-attribute instance-attribute

template = 'django_spire/component/scroll/crud_scroll.html' class-attribute instance-attribute

item_delete_options = DeleteOptions() class-attribute

item_form_options = None class-attribute

can_create property

Whether createItem() can open the form: a form page guards itself, and a form component needs ADD access.

can_edit property

Whether editItem() can open the form on a row: a form page guards itself, and a form component needs CHANGE access. A list whose rows are only ever created overrides it to False, and load_item_form() then refuses a row.

can_delete property

Whether deleteItem() can delete a row: a delete page guards itself, and a confirmation needs DELETE access.

__init_subclass__

Source code in django_spire/core/components/scroll/model_crud_component.py
def __init_subclass__(cls, **kwargs: Any) -> None:
    super().__init_subclass__(**kwargs)

    if cls.item_delete_options is not None and not isinstance(
        cls.item_delete_options,
        cls.DeleteOptions | cls.PageDeleteOptions,
    ):
        message = (
            f'{cls.__name__}.item_delete_options must be a '
            'ModelCrudScrollComponent.DeleteOptions, a '
            'ModelCrudScrollComponent.PageDeleteOptions, or None.'
        )
        raise ImproperlyConfigured(message)

    if cls.item_form_options is not None and not isinstance(
        cls.item_form_options,
        cls.FormOptions | cls.PageFormOptions,
    ):
        message = (
            f'{cls.__name__}.item_form_options must be a '
            'ModelCrudScrollComponent.FormOptions, a '
            'ModelCrudScrollComponent.PageFormOptions, or None.'
        )
        raise ImproperlyConfigured(message)

get_item_form_options

Source code in django_spire/core/components/scroll/model_crud_component.py
def get_item_form_options(self) -> FormOptions | PageFormOptions | None:
    return self.item_form_options

get_item_delete_options

Source code in django_spire/core/components/scroll/model_crud_component.py
def get_item_delete_options(self) -> DeleteOptions | PageDeleteOptions | None:
    return self.item_delete_options

load_item_delete_confirmation

Source code in django_spire/core/components/scroll/model_crud_component.py
@Glue.attr(required_access=Glue.Access.DELETE)
def load_item_delete_confirmation(self, pk: int | str) -> BaseModelDeleteConfirmationComponent:
    options = self.get_item_delete_options()
    if not isinstance(options, self.DeleteOptions):
        message = f'{type(self).__name__} has no confirmation component to delete a row with.'
        raise PermissionDenied(message)

    return options.component(
        instance=self.get_instance(pk),
        access=self.access,
    )

load_item_form

The form that creates a row, or with pk edits one. ADD access is the least that opens any form. The form then guards what it does: it takes this list's access, and Glue's required_save_access lets its fields and save change a saved row only at CHANGE. A form component that mixes in Glue.ModelAccessRequiredMixin also refuses to open for a user without that access. can_edit refuses a row before any form is built: below CHANGE, and in a list whose rows are never edited, which no access expresses.

Source code in django_spire/core/components/scroll/model_crud_component.py
@Glue.attr(required_access=Glue.Access.ADD)
def load_item_form(self, pk: int | str | None = None) -> ModelFormComponent:
    """
    The form that creates a row, or with ``pk`` edits one. ``ADD`` access
    is the least that opens any form. The form then guards what it does:
    it takes this list's access, and Glue's ``required_save_access`` lets
    its fields and save change a saved row only at ``CHANGE``. A form
    component that mixes in ``Glue.ModelAccessRequiredMixin`` also refuses
    to open for a user without that access. ``can_edit`` refuses a row
    before any form is built: below ``CHANGE``, and in a list whose rows
    are never edited, which no access expresses.
    """
    options = self.get_item_form_options()
    if not isinstance(options, self.FormOptions):
        message = f'{type(self).__name__} has no form component to create or edit a row with.'
        raise PermissionDenied(message)

    if pk is not None:
        if not self.can_edit:
            message = f'{type(self).__name__} does not allow its rows to be edited.'
            raise PermissionDenied(message)

        self.get_instance(pk)

    return options.build_component(
        model_pk=pk,
        access=self.access,
    )

QuerySetScrollComponent

Bases: BaseScrollComponent, ABC

A :class:BaseScrollComponent whose items are the rows of a queryset.

Subclasses return the rows from get_queryset(). The primary key identifies each row and is appended to the queryset's ordering, so that the order is total; a queryset with no ordering is listed by primary key. Each item is a model instance.

glue_items sends each row to the browser as the Glue model get_glue_item() builds, in place of rendering it on the server, so the row markup can call the model's Glue methods. The rows are drawn in the browser: item_template is Alpine markup that reads item, drawn by the scroll_item block of the component template, which a list may fill in itself instead. The browser then loads rows with load_glue_items() and load_glue_item(), and the other loads are refused.

Glue rows never arrive with the render: a Glue child is not derived again when its component refreshes, so every batch comes from load_glue_items(). A batch holds up to batch_size rows, and a full one means there may be more.

glue_items = False class-attribute

model_name cached property

verbose_name cached property

verbose_name_plural cached property

renders_items_on_server property

__init_subclass__

Source code in django_spire/core/components/scroll/queryset_component.py
def __init_subclass__(cls, **kwargs: Any) -> None:
    super().__init_subclass__(**kwargs)

    if cls.glue_items and cls.get_glue_item is QuerySetScrollComponent.get_glue_item:
        message = (
            f'{cls.__name__} sends Glue items, which needs get_glue_item(): override it '
            "to build each row's Glue model."
        )
        raise ImproperlyConfigured(message)

get_queryset abstractmethod

Return the rows this scroll lists, in the order it lists them.

Source code in django_spire/core/components/scroll/queryset_component.py
@abstractmethod
def get_queryset(self) -> QuerySet:
    """Return the rows this scroll lists, in the order it lists them."""

get_permission_model

Return the listed model, whose permissions Glue.ModelAccessMixin reads.

Source code in django_spire/core/components/scroll/queryset_component.py
def get_permission_model(self) -> type[Model]:
    """Return the listed model, whose permissions ``Glue.ModelAccessMixin`` reads."""
    return self.get_queryset().model

get_items

Source code in django_spire/core/components/scroll/queryset_component.py
def get_items(self, offset: int, limit: int) -> list[Model]:
    queryset = self.get_queryset()
    ordering = queryset.query.order_by or queryset.model._meta.ordering

    return list(queryset.order_by(*ordering, 'pk')[offset:offset + limit])

get_item

Source code in django_spire/core/components/scroll/queryset_component.py
def get_item(self, key: Any) -> Model | None:
    try:
        return self.get_queryset().filter(pk=key).first()
    except (TypeError, ValueError, ValidationError):
        return None

get_item_key

Source code in django_spire/core/components/scroll/queryset_component.py
def get_item_key(self, item: Model) -> Any:
    return item.pk

get_instance

Return the row of get_queryset() with this primary key, for a callable that acts on one row. A row that is not in the list is reported as Glue's model_instance_not_found, a 404.

Source code in django_spire/core/components/scroll/queryset_component.py
def get_instance(self, pk: Any) -> Model:
    """
    Return the row of ``get_queryset()`` with this primary key, for a
    callable that acts on one row. A row that is not in the list is
    reported as Glue's ``model_instance_not_found``, a 404.
    """
    queryset = self.get_queryset()

    try:
        return queryset.get(pk=pk)
    except queryset.model.DoesNotExist as error:
        raise GlueModelInstanceNotFoundError(queryset.model._meta.label, pk) from error

get_glue_item

Return the Glue model the browser receives for item when glue_items is set, built with name as its unique name and with exactly the fields, access and form the row needs. A list that sets glue_items must override it.

To edit a row in place, pass the row a form, bind the row's inputs to item.form, and save with the form's own method, such as item.form.save_model_obj(). That runs the form's validation and whatever the application's save does. item.save() writes the model directly instead.

Source code in django_spire/core/components/scroll/queryset_component.py
def get_glue_item(self, item: Model, name: str) -> Glue.Model:
    """
    Return the Glue model the browser receives for ``item`` when
    ``glue_items`` is set, built with ``name`` as its unique name and with
    exactly the fields, access and form the row needs. A list that sets
    ``glue_items`` must override it.

    To edit a row in place, pass the row a ``form``, bind the row's inputs
    to ``item.form``, and save with the form's own method, such as
    ``item.form.save_model_obj()``. That runs the form's validation and
    whatever the application's save does. ``item.save()`` writes the model
    directly instead.
    """
    raise NotImplementedError

load_glue_item

Source code in django_spire/core/components/scroll/queryset_component.py
@Glue.attr
def load_glue_item(self, key: int | str) -> Glue.Model | None:
    self._refuse_unless_glue_items()

    item = self.get_item(key)

    if item is None:
        return None

    return self._get_named_glue_item(item)

load_glue_items

Source code in django_spire/core/components/scroll/queryset_component.py
@Glue.attr
def load_glue_items(self, offset: int) -> Glue.Sequence:
    self._refuse_unless_glue_items()
    self._validate_offset(offset)

    return Glue.Sequence(
        [self._get_named_glue_item(item) for item in self.get_items(offset, self.batch_size)],
        name=f'batch_{offset}',
        access=self.access,
    )

SearchAndSortScrollMixin

Adds search and optional sort :class:Glue.ComponentField attributes to a scroll component without writing a boilerplate FilterForm.

Declare default_sort as a Django Choices member (e.g. SolutionSortChoices.NAME) and sort_choices is inferred from type(default_sort) automatically. Or declare sort_choices alone to default to its first choice. Omit both for a search-only list.

sort_choices = None class-attribute

default_sort = None class-attribute

search instance-attribute

__init_subclass__

Source code in django_spire/core/components/scroll/search_and_sort_scroll_mixin.py
def __init_subclass__(cls, **kwargs: Any) -> None:
    if issubclass(cls, Glue.Component) and not any(
        'search' in base.__dict__ for base in cls.__mro__
    ):
        search_declaration = Glue.ComponentField(forms.CharField(required=False))
        search_declaration.__set_name__(cls, 'search')
        cls.search = search_declaration

    own_sort_choices = cls.__dict__.get('sort_choices')
    own_default_sort = cls.__dict__.get('default_sort')

    if own_sort_choices is None and isinstance(own_default_sort, models.Choices):
        cls.sort_choices = type(own_default_sort)
    elif cls.sort_choices is None and cls.default_sort is not None:
        if isinstance(cls.default_sort, models.Choices):
            cls.sort_choices = type(cls.default_sort)
        else:
            message = (
                f'{cls.__name__}.default_sort must be a Django Choices member '
                'when sort_choices is not set.'
            )
            raise ImproperlyConfigured(message)

    has_inherited_sort = any('sort' in base.__dict__ for base in cls.__mro__)

    if issubclass(cls, Glue.Component) and cls.sort_choices is not None and (
        'sort' not in cls.__dict__
        and (not has_inherited_sort or own_sort_choices is not None or own_default_sort is not None)
    ):
        if not (isinstance(cls.sort_choices, type) and issubclass(cls.sort_choices, models.Choices)):
            message = f'{cls.__name__}.sort_choices must be a Django Choices subclass.'
            raise ImproperlyConfigured(message)

        if cls.default_sort is not None:
            try:
                initial = cls.sort_choices(cls.default_sort)
            except ValueError as error:
                message = (
                    f'{cls.__name__}.default_sort ({cls.default_sort!r}) is not a valid '
                    f'{cls.sort_choices.__name__} choice.'
                )
                raise ImproperlyConfigured(message) from error
        else:
            initial = cls.sort_choices(cls.sort_choices.choices[0][0])

        sort_declaration = Glue.ComponentField(
            forms.TypedChoiceField(
                choices=cls.sort_choices.choices,
                coerce=cls.sort_choices,
                initial=initial,
            )
        )
        sort_declaration.__set_name__(cls, 'sort')
        cls.sort = sort_declaration

    super().__init_subclass__(**kwargs)

Tab dataclass

Declares one tab inside a :class:TabsComponent.

Provide exactly one target: - component: a Glue.Component class or zero-argument factory callable (e.g. partial(EmployeeListComponent, is_active=True)) - view_url: a Django route URL loaded lazily via Glue.view(url) - template: a Django template rendered into the pane (with optional context) - href: a full-page link rendered as an <a> tag instead of swapping panes

id instance-attribute

label instance-attribute

component = None class-attribute instance-attribute

view_url = None class-attribute instance-attribute

template = None class-attribute instance-attribute

context = field(default_factory=dict) class-attribute instance-attribute

href = None class-attribute instance-attribute

icon = None class-attribute instance-attribute

cache = None class-attribute instance-attribute

view_method = 'GET' class-attribute instance-attribute

kind property

is_component property

is_view property

is_template property

__post_init__

Source code in django_spire/core/components/tab/options.py
def __post_init__(self) -> None:
    if not isinstance(self.id, str) or not self.id.strip():
        message = 'Tab.id must be a non-empty string.'
        raise ValueError(message)

    if not isinstance(self.label, str) or not self.label.strip():
        message = 'Tab.label must be a non-empty string.'
        raise ValueError(message)

    targets = [
        name
        for name, value in (
            ('component', self.component),
            ('view_url', self.view_url),
            ('template', self.template),
            ('href', self.href),
        )
        if value is not None
    ]

    if len(targets) != 1:
        message = (
            f'Tab {self.id!r} must set exactly one of component, view_url, template, or href; '
            f'got {targets or "none"}.'
        )
        raise ValueError(message)

    if self.component is not None and not callable(self.component):
        message = f'Tab {self.id!r} component must be a Glue.Component class or factory callable.'
        raise TypeError(message)

    if self.view_method not in ('GET', 'POST'):
        message = f'Tab {self.id!r} view_method must be "GET" or "POST", not {self.view_method!r}.'
        raise ValueError(message)

build_component

Source code in django_spire/core/components/tab/options.py
def build_component(self) -> Glue.Component:
    if self.component is None:
        message = f'Tab {self.id!r} does not have a component.'
        raise ValueError(message)

    instance = self.component()

    if not isinstance(instance, Glue.Component):
        message = (
            f'Tab {self.id!r} component factory must return a Glue.Component instance, '
            f'got {type(instance).__name__}.'
        )
        raise TypeError(message)

    return instance

TabsComponent

Bases: Component, ABC

A tabbed container whose panes are loaded lazily and may host Glue components, Django fragment views (via Glue.view), plain templates, or full-page links.

Subclasses implement get_tabs() returning a sequence of :class:Tab items (aliased as self.Tab). Only the initially active tab is rendered on first paint; other tabs stay empty until selected.

  • url_param: query parameter synced with history.replaceState and read from request.GET on first render (default 'tab'; set to None to disable).
  • cache_tabs: whether visited panes stay mounted across switches (default True; overridable per tab via Tab(..., cache=False)).
  • tab_invalidated: Glue event wired to invalidateTab(tab_id) so listeners can mark a cached tab stale or force-refresh the active tab.

Tab = Tab class-attribute instance-attribute

template = 'django_spire/component/tab/tabs.html' class-attribute instance-attribute

view_template = 'django_spire/component/page/full_page.html' class-attribute instance-attribute

url_param = 'tab' class-attribute

default_tab = None class-attribute

cache_tabs = True class-attribute

active_tab = Glue.ComponentParameter(None) class-attribute instance-attribute

tab_invalidated = Glue.event() class-attribute instance-attribute

tabs cached property

active_tab_obj property

active_tab_html cached property

tabs_config_json property

__post_init__

Source code in django_spire/core/components/tab/tabs_component.py
def __post_init__(self, request: HttpRequest) -> None:
    super().__post_init__(request)

    valid_pane_ids = [tab.id for tab in self.tabs if not tab.is_link]

    if not valid_pane_ids:
        self.active_tab = None
        return

    if self.active_tab not in valid_pane_ids:
        requested_tab_id = request.GET.get(self.url_param) if self.url_param else None

        if requested_tab_id in valid_pane_ids:
            self.active_tab = requested_tab_id
        elif self.default_tab in valid_pane_ids:
            self.active_tab = self.default_tab
        else:
            self.active_tab = valid_pane_ids[0]

get_tabs abstractmethod

Return the ordered :class:Tab definitions to display.

Source code in django_spire/core/components/tab/tabs_component.py
@abstractmethod
def get_tabs(self) -> Sequence[Tab]:
    """Return the ordered :class:`Tab` definitions to display."""

get_tab

Source code in django_spire/core/components/tab/tabs_component.py
def get_tab(self, tab_id: str | None) -> Tab | None:
    if tab_id is None:
        return None

    for tab in self.tabs:
        if tab.id == tab_id:
            return tab

    return None

should_cache_tab

Source code in django_spire/core/components/tab/tabs_component.py
def should_cache_tab(self, tab: Tab) -> bool:
    return self.cache_tabs if tab.cache is None else tab.cache

load_tab

Source code in django_spire/core/components/tab/tabs_component.py
@Glue.attr(required_access=Glue.Access.VIEW, skip_rerender=True)
def load_tab(self, request: HttpRequest, tab_id: str) -> GlueResponse:
    tab = self.get_tab(tab_id)

    if tab is None or tab.is_link or tab.is_view:
        message = f'{type(self).__name__} has no loadable tab {tab_id!r}.'
        raise PermissionDenied(message)

    if tab.is_component:
        try:
            return self._render_component_tab(request, tab)
        except GlueAuthorizationError as error:
            raise PermissionDenied from error

    return GlueTemplateResponse(
        request,
        tab.template,
        {**tab.context, 'component': self, 'tab': tab},
    )