Skip to content

Scroll Components

Purpose: Show an infinite list as a Glue component that loads its rows a batch at a time, updates one row at a time, and can create, edit and delete its rows.


Why Scroll Components?

A list page usually needs the same things: load more rows as the user scrolls, reload when a search or filter changes, and redraw a row after it is edited. The scroll components provide:

  • Paging on the server, one query per batch, with no position held between requests
  • Rows rendered on the server from a template, or sent as Glue models that edit themselves in place
  • Search and filter controls declared on the component and applied with one call
  • Updates to a single row by key, from the browser or from a callable
  • Ready-made create, edit and delete, each in a modal or on a page
  • Lists of anything: a queryset, an API, or any source that can return a batch

They sit beside the older template scroll in django_spire/glue/scroll/, which is unchanged. See Filtering for that one.


Quick Start

1. Write the list component

from django_spire.core.components import QuerySetScrollComponent

from app.task.models import Task


class TaskListComponent(QuerySetScrollComponent):
    item_template = 'task/item/task_row.html'
    view_template = 'django_spire/component/page/full_page.html'

    def get_queryset(self):
        return Task.objects.active().order_by('name')

2. Write the row template

{% extends 'django_spire/component/scroll/item/item.html' %}

{% block scroll_item_class %}row border-bottom py-2{% endblock %}

{% block scroll_item_content %}
    <div class="col">
        <a href="{% url 'task:page:detail' pk=item.pk %}">{{ item.name }}</a>
    </div>
    <div class="col-auto text-muted">{{ item.get_status_display }}</div>
{% endblock %}

The row template extends item.html, which gives the row the attribute the list finds it by. The row receives item, the model instance, so it can use anything a Django template can, such as get_status_display. Load anything a row reads from a related model in get_queryset(), with select_related or prefetch_related, so a batch stays one query.

3. Add a route

from django.contrib.auth.decorators import login_required
from django.urls import path

from app.task.components import TaskListComponent

urlpatterns = [
    path('list/', login_required(TaskListComponent.as_view()), name='list'),
]

The page now lists the first 25 tasks and loads 25 more each time the user nears the bottom.


Core Concepts

BaseScrollComponent

The base of every scroll. It owns paging and all behaviour in the browser, and knows nothing about where its items come from. A subclass supplies the items through three methods.

from django_spire.core.components import BaseScrollComponent
Method Description
get_items(offset, limit) Return up to limit items starting at offset, in an order that is the same on every call
get_item(key) Return the item with this key, or None when it no longer belongs in the list
get_item_key(item) Return the value that identifies an item among all items
Setting Description
template The list's template. It must extend django_spire/component/scroll/scroll.html
item_template The markup for one row, rendered on the server. It must extend item/item.html or item/table_item.html
batch_size How many rows are loaded at a time. Defaults to 25
view_template The page the component is shown in when served by as_view()

The templates are checked the first time each list is shown, and a list whose templates do not extend these raises ImproperlyConfigured.

QuerySetScrollComponent

A scroll over the rows of a queryset. It fills in the three item methods, so a subclass writes get_queryset().

from django_spire.core.components import QuerySetScrollComponent
Member Description
get_queryset() Return the rows the list shows, in the order it shows them
get_instance(pk) Return one row of the queryset for a callable that acts on it. A row outside the list is reported as a 404

The primary key is added to the end of the queryset's ordering, so rows that tie on the ordering never repeat or go missing between batches. A queryset with no ordering is listed by primary key. Each item is the model instance.

Glue rows

A queryset scroll can send each row to the browser as a Glue model instead of rendering it on the server, so the row's markup can call the model's Glue methods and save its fields.

Member Description
glue_items True sends the rows as Glue models. False, the default, renders them on the server
get_glue_item(item, name) Build the Glue model for one row, with name as its unique_name. A list that sets glue_items must override it, and is refused when it is defined otherwise

get_glue_item() is where a list says exactly what each row exposes: its fields, its access, and any form. Pass access=self.access for the row to have the list's access.

The rows are drawn in the browser, so item_template is Alpine markup that reads item and must not extend item/item.html or item/table_item.html. A list may leave it out and fill the scroll_item block of its own template instead. A Glue row costs more to send than a rendered row, so use it for lists whose rows are edited in place.

ModelCrudScrollComponent

A queryset scroll with create, edit and delete.

from django_spire.core.components import ModelCrudScrollComponent
Setting Description
item_form_options How a row is created and edited. None, the default, means the list has neither
item_delete_options How a row is deleted. The default is a confirmation that soft-deletes. None turns deleting off

Only rows in get_queryset() can be edited or deleted, and each action checks the user's access.

Form and delete options

Each action happens in a component shown in a modal, or on a page. The class of the options object says which. The four classes are attributes of ModelCrudScrollComponent, so a list needs no other import.

Options Arguments Description
ModelCrudScrollComponent.FormOptions component, or form_class with template A form component in a modal. See Form Components
ModelCrudScrollComponent.PageFormOptions url_name, create_url_name, return_url_name A form page. url_name takes the row's key as pk
ModelCrudScrollComponent.DeleteOptions component A confirmation in a modal. See Confirmation Components
ModelCrudScrollComponent.PageDeleteOptions url_name, return_url_name A delete page. url_name takes the row's key as pk

With PageFormOptions, creating goes to create_url_name, or to url_name with a pk of 0 when that is left out.

A page link carries a return_url query parameter: the route named by return_url_name, or the address the list is shown at. A page that reads return_url sends the user back there afterwards.

Templates

Template Description
django_spire/component/scroll/scroll.html The list. Every list template extends it, directly or through one of the next two
django_spire/component/scroll/table_scroll.html The list as a table
django_spire/component/scroll/crud_scroll.html The list with create, edit and delete
django_spire/component/scroll/item/item.html One server-rendered row, as a div
django_spire/component/scroll/item/table_item.html One server-rendered row, as a tr
django_spire/component/page/full_page.html A full page that shows one component
Block In Description
scroll_header scroll.html Markup above the rows, such as a search box or a New button
scroll_item scroll.html One Glue row, drawn in the browser. Draws item_template unless overridden
scroll_empty scroll.html What is shown when the list has no rows
scroll_loading scroll.html What is shown while a batch loads
scroll_footer scroll.html Markup below the rows
scroll_container_class scroll.html Classes on the list's outer element
scroll_table_header table_scroll.html The table's header row
scroll_table_class table_scroll.html Classes on the table
scroll_item_content item/item.html, item/table_item.html The content of one server-rendered row
scroll_item_class item/item.html, item/table_item.html Classes on one server-rendered row

In the browser

Markup inside the list can read the list's state and call its methods.

Name Description
items, keys The Glue rows shown and their keys
loadedCount How many rows are shown
hasMore Whether another batch may exist
isLoading Whether a batch is loading
reloadItems() Send the controls to the server and show the first batch again
addItem(key) Fetch one row and put it at the top
refreshItem(key) Fetch one row again and redraw it. A row the server no longer has is removed
removeItem(key) Take one row out of the list
createItem(), editItem(item), deleteItem(item) The CRUD actions. Each of the last two takes the item or its key

Main Operations

Listing as a Table

class TaskTableComponent(QuerySetScrollComponent):
    template = 'task/component/task_table.html'
    item_template = 'task/item/task_table_row.html'

    def get_queryset(self):
        return Task.objects.active().order_by('name')
{% extends 'django_spire/component/scroll/table_scroll.html' %}

{% block scroll_table_header %}
    <tr>
        <th>Name</th>
        <th>Status</th>
    </tr>
{% endblock %}
{% extends 'django_spire/component/scroll/item/table_item.html' %}

{% block scroll_item_content %}
    <td>{{ item.name }}</td>
    <td>{{ item.get_status_display }}</td>
{% endblock %}

The list template extends table.html and fills in the header. The row extends table_row.html. The two row templates share their block names, so a row moves between a div and a tr by changing only the template it extends.

Adding Search and Filters

from django_glue import Glue

from app.task.choices import TaskStatusChoices


class TaskListComponent(QuerySetScrollComponent):
    template = 'task/component/task_list.html'
    item_template = 'task/item/task_row.html'

    status_choices = tuple(TaskStatusChoices.choices)

    search: str = Glue.attr('', editable=True)
    status: str = Glue.attr('', editable=True)

    def get_queryset(self):
        queryset = Task.objects.active().search(self.search)

        if self.status in TaskStatusChoices.values:
            queryset = queryset.filter(status=self.status)

        return queryset.order_by('name')
{% extends 'django_spire/component/scroll/scroll.html' %}

{% block scroll_header %}
    <div class="row g-2 pb-3">
        <div class="col">
            <input
                class="form-control"
                placeholder="Search tasks ..."
                type="search"
                x-model="component.search"
                @input.debounce="reloadItems()"
            >
        </div>
        <div class="col-auto">
            <select class="form-select" x-model="component.status" @change="reloadItems()">
                <option value="">Any status</option>
                {% for value, label in component.status_choices %}
                    <option value="{{ value }}">{{ label }}</option>
                {% endfor %}
            </select>
        </div>
    </div>
{% endblock %}

A control is an editable attribute on the component. The markup binds an input to it, and reloadItems() sends its value to the server and shows the first batch again. The component reads the value where it builds its queryset. Check a value against what is allowed before using it, as status is here, because it comes from the browser.

Acting on a Row From a Callable

class TaskListComponent(QuerySetScrollComponent):
    item_template = 'task/item/task_row.html'

    def get_queryset(self):
        return Task.objects.active().order_by('name')

    @Glue.attr(required_access=Glue.Access.CHANGE, skip_rerender=True)
    def complete(self, pk: int) -> None:
        self.get_instance(pk).services.processor.complete()
        self.item_changed(key=pk)
{% extends 'django_spire/component/scroll/item/item.html' %}

{% block scroll_item_class %}row border-bottom py-2 align-items-center{% endblock %}

{% block scroll_item_content %}
    <div class="col">{{ item.name }}</div>
    <div class="col-auto">
        <button
            class="btn btn-sm btn-outline-success"
            type="button"
            title="Complete Task"
            x-bind="asyncButton(() => component.complete({pk: {{ item.pk }}}))"
        >
            <i class="bi bi-check-lg"></i>
        </button>
    </div>
{% endblock %}

get_instance(pk) looks the row up inside the list's own queryset, so a callable cannot reach a row the list does not show. skip_rerender=True stops the whole list from being redrawn, and firing item_changed redraws that one row. Fire item_added or item_removed in the same way for a row that was created or taken away.

The button is an async button, so a second click sends nothing while the first is running.

Creating, Editing and Deleting

from django_spire.core.components import ModelCrudScrollComponent

from app.task.forms import TaskForm


class TaskListComponent(ModelCrudScrollComponent):
    template = 'task/component/task_list.html'
    item_template = 'task/item/task_row.html'

    item_form_options = ModelCrudScrollComponent.FormOptions(
        form_class=TaskForm,
        template='task/form/task_form.html',
    )

    def __post_init__(self, request):
        super().__post_init__(request)

        if request.user.has_perm('task.delete_task'):
            self.access = Glue.Access.DELETE
        elif request.user.has_perm('task.change_task'):
            self.access = Glue.Access.CHANGE

    def get_queryset(self):
        return Task.objects.active().order_by('name')
{% extends 'django_spire/component/scroll/crud_scroll.html' %}

{% block scroll_header %}
    {% if component.can_create %}
        <div class="text-end pb-3">
            <button class="btn btn-sm btn-primary text-light" type="button" @click="createItem()">
                <i class="bi bi-plus"></i> New Task
            </button>
        </div>
    {% endif %}
{% endblock %}
{% extends 'django_spire/component/scroll/item/item.html' %}

{% block scroll_item_class %}row border-bottom py-2 align-items-center{% endblock %}

{% block scroll_item_content %}
    <div class="col">{{ item.name }}</div>
    <div class="col-auto">
        {% if component.can_edit %}
            <button class="btn btn-sm btn-outline-secondary" type="button" title="Edit Task" @click="editItem({{ item.pk }})">
                <i class="bi bi-pencil"></i>
            </button>
        {% endif %}
        {% if component.can_delete %}
            <button class="btn btn-sm btn-outline-danger" type="button" title="Delete Task" @click="deleteItem({{ item.pk }})">
                <i class="bi bi-trash"></i>
            </button>
        {% endif %}
    </div>
{% endblock %}

The list template extends crud.html, which adds createItem(), editItem(item) and deleteItem(item). With these options the form opens in a modal and the new or changed row appears in the list when it is saved. Deleting asks for confirmation and soft-deletes the row.

Creating needs ADD access, editing needs CHANGE and deleting needs DELETE. A component starts with VIEW, so set self.access from what the user may do. To show a button only to a user who can use it, put it under {% if component.can_create %}, {% if component.can_edit %} or {% if component.can_delete %}, as the list and row above do. Each is true when the list uses a page, which guards itself, or a component and its access allows ADD, CHANGE or DELETE. Read them from the component rather than from perms: a row loaded or refreshed after the first render has only component in its context.

load_item_form() asks only for ADD, the least that opens any form, and the form guards the rest. It takes the list's access, and its fields and save change a saved row only at CHANGE. To refuse even to open an edit form for a user without CHANGE, mix Glue.ModelAccessRequiredMixin into the form component: ModelFormComponent.get_required_access() asks for ADD to create and CHANGE to edit.

A list whose rows are created but never edited, such as a list of memberships that are only added and removed, overrides can_edit to return False. Edit then leaves its rows, and load_item_form() refuses a row, so the form can still only create:

class MemberListComponent(ModelCrudScrollComponent):
    @property
    def can_edit(self) -> bool:
        return False

For a ⋮ menu in place of the buttons, include model_crud_actions_dropdown.html in the row. Its Edit and Delete call editItem() and deleteItem(), so it works with modals and pages, and it shows each one by can_edit and can_delete:

{% url 'task:page:detail' pk=item.pk as task_url %}
{% include 'django_spire/dropdown/model_crud_actions_dropdown.html' with view_url=task_url %}

view_url adds a View link, and delete_label renames Delete, such as delete_label='Remove'.

To take it from the user's permissions on the listed model, mix in django-glue's ModelAccessMixin:

class TaskListComponent(Glue.ModelAccessMixin, ModelCrudScrollComponent):
    ...

The list already knows its model from get_queryset(), so nothing else is needed: view_task gives VIEW, and holding add_task, change_task and delete_task as well gives DELETE. A level counts only when every level below it is held too. To read another model's permissions, such as the parent app's in a sub-app, set permission_model = Task on the list. Assign self.access after super().__post_init__(request) to decide differently. Spire's form and model confirmation components name their model the same way and take the mixin too.

To also turn away a user without view_task, mix in ModelAccessRequiredMixin in its place. It sets the access the same way, and redirects a user without the permission to log in, so the list's URL needs no permission_required.

Using Pages for the Form or the Delete

class TaskListComponent(ModelCrudScrollComponent):
    item_form_options = ModelCrudScrollComponent.PageFormOptions(
        'task:form:update',
        create_url_name='task:form:create',
    )
    item_delete_options = ModelCrudScrollComponent.PageDeleteOptions('task:form:delete')

The same three methods then send the user to those pages. Use this when the app already has form and delete views. Each link carries return_url, so a view that reads it brings the user back to the list.

Deleting Another Way

from django_spire.core.components import (
    BaseModelDeleteConfirmationComponent,
    ModelCrudScrollComponent,
    ModelDeleteConfirmationComponent,
)


class TaskArchiveConfirmationComponent(BaseModelDeleteConfirmationComponent):
    def perform_action(self) -> None:
        self.instance.services.processor.archive()


class TaskListComponent(ModelCrudScrollComponent):
    item_delete_options = ModelCrudScrollComponent.DeleteOptions(
        component=TaskArchiveConfirmationComponent,
    )


class AuditLogListComponent(ModelCrudScrollComponent):
    item_delete_options = ModelCrudScrollComponent.DeleteOptions(
        component=ModelDeleteConfirmationComponent,
    )

The first list deletes through its own confirmation. The second deletes the row from the database, where the default only marks it deleted. Set item_delete_options = None for a list that cannot delete.

Editing a Row in Place

from django_glue import Glue

from django_spire.core.components import QuerySetScrollComponent


class TaskListComponent(QuerySetScrollComponent):
    item_template = 'task/item/task_glue_row.html'
    glue_items = True

    status_choices = tuple(TaskStatusChoices.choices)

    def get_queryset(self):
        return Task.objects.active().order_by('name')

    def get_glue_item(self, item, name):
        return Glue.model(
            target=item,
            unique_name=name,
            access=self.access,
            fields=('name', 'status'),
            form=TaskForm,
        )
<div class="row border-bottom py-2 align-items-center">
    <div class="col" x-text="item.name"></div>
    <div class="col-auto">
        <select
            class="form-select form-select-sm"
            aria-label="Task status"
            x-model="item.form.status"
            @change="
                await item.form.save_model_obj()
                refreshItem(item.$pk)
            "
        >
            {% for value, label in component.status_choices %}
                <option value="{{ value }}">{{ label }}</option>
            {% endfor %}
        </select>
    </div>
</div>

Each row is a Glue model with the form attached. The select is bound to the row's form, and changing it saves through the form's own method, which runs the form's validation and the application's save. The row's key is item.$pk.

Listing Something That Is Not a Queryset

from django_spire.core.components import BaseScrollComponent


class CustomerListComponent(BaseScrollComponent):
    item_template = 'customer/item/customer_row.html'

    def get_items(self, offset, limit):
        return crm_client.customers(skip=offset, limit=limit)

    def get_item(self, key):
        return crm_client.customer(key)

    def get_item_key(self, item):
        return item.id

Pass offset and limit on to the source so that each batch is one request to it. Return None from get_item for an item the source no longer has, and the list removes its row.

Testing a List

from django_spire.testing.playwright import ScrollComponent


def test_scrolling_loads_every_task(page, demo_start):
    demo_start().goto('task:page:list')

    scroll = ScrollComponent(page, row_selector='[data-task-row]')
    scroll.scroll_until_row_count(60)

    assert scroll.state()['hasMore'] is False

ScrollComponent is a Playwright helper that waits on the list's own state, so a test never sleeps. Give it a selector that matches one row of the list under test.


Things to Know

  • A project that does not extend Spire's base.html must load the scripts in django_spire/js/components/ itself.
  • A form or a confirmation acts on the row it was opened for. The list checks that the row is in its queryset when the prompt opens, and not again when the user saves or confirms. A list whose queryset is a permission rule should scope the lookup in its own component. See Confirmation Components.
  • Paging is by offset. A row inserted while a user scrolls can make a row repeat or be skipped. Reloading the list corrects it.