Skip to content

form

django_spire.core.components.form

__all__ = ['BaseFormComponent', 'FormComponent', 'FormOptions', 'ModelFormComponent', 'PageFormOptions'] module-attribute

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'

FormOptions dataclass

A row is created and edited in a form component, shown in a modal. Give the application's own component (a :class:ModelFormComponent class or a callable factory such as functools.partial(...)), or a form_class with the template that lays out its fields, which the generic :class:ModelFormComponent shows. The form fires saved with the row's pk.

component = None class-attribute instance-attribute

form_class = None class-attribute instance-attribute

template = None class-attribute instance-attribute

__post_init__

Source code in django_spire/core/components/form/options.py
def __post_init__(self) -> None:
    if self.component is not None:
        if isinstance(self.component, type):
            if not issubclass(self.component, ModelFormComponent):
                message = 'FormOptions.component must be a ModelFormComponent subclass or callable factory.'
                raise ImproperlyConfigured(message)
        elif not callable(self.component):
            message = 'FormOptions.component must be a ModelFormComponent subclass or callable factory.'
            raise ImproperlyConfigured(message)

    if self.component is not None and (
        self.form_class is not None or self.template is not None
    ):
        message = (
            'FormOptions takes a component, or a form_class with a template, '
            'not both: a component declares its own form and template.'
        )
        raise ImproperlyConfigured(message)

    if self.component is None and (self.form_class is None or self.template is None):
        message = (
            'FormOptions needs a component, or a form_class together with a '
            'template.'
        )
        raise ImproperlyConfigured(message)

build_component

Source code in django_spire/core/components/form/options.py
def build_component(self, **parameters: Any) -> ModelFormComponent:
    if self.component is not None:
        built_component = self.component(**parameters)

        if not isinstance(built_component, ModelFormComponent):
            message = (
                f'FormOptions.component factory must return a ModelFormComponent, '
                f'got {type(built_component).__name__}.'
            )
            raise ImproperlyConfigured(message)

        return built_component

    return ModelFormComponent(
        form_class=self.form_class,
        template=self.template,
        **parameters,
    )

PageFormOptions dataclass

A row is created and edited on a page of its own. url_name is the route that takes the row's key as pk. Creating a row goes to create_url_name, which takes no arguments, or when that is left out, to url_name with a pk of 0.

Each link carries a return_url for the page to send the user to afterwards: the route named by return_url_name, or when that is left out, the address the list is shown at. A page that does not read return_url goes wherever it always does.

url_name instance-attribute

create_url_name = None class-attribute instance-attribute

return_url_name = None class-attribute instance-attribute