Skip to content

scroll

django_spire.core.components.scroll

__all__ = ['BaseScrollComponent', 'ModelCrudScrollComponent', 'QuerySetScrollComponent', 'SearchAndSortScrollMixin'] module-attribute

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)