Source code for ferrosoft.apps.emiflow.widgets
# Copyright (c) 2024 Ferrosoft GmbH. All rights reserved.
"""Custom Django form widgets used by emiflow forms and tables."""
from django.forms.widgets import Widget
from ferrosoft.apps.emiflow.models import (
EmissionFactor,
)
[docs]
class EmissionFactorWidget(Widget):
"""Hidden picker widget that surfaces a selected :class:`EmissionFactor`.
The form posts the factor's primary key, but the rendered template
needs the full object to show a human-readable preview. This widget
looks up the bound factor and exposes it to the template via the
``emission_factor`` context key while keeping the underlying input
hidden.
"""
template_name = "emiflow/picker/emission_factor/widget.html"
[docs]
def get_context(self, name, value, attrs):
"""Resolve the bound factor (if any) and force the input ``type`` to ``hidden``."""
context = super().get_context(name, value, attrs)
if value:
context["emission_factor"] = EmissionFactor.objects.get(pk=value)
context["widget"]["type"] = "hidden"
return context
[docs]
class EditDeleteActionsWidget(Widget):
"""Row-actions widget rendering edit and delete buttons for a table row.
The button URLs are produced by per-row callables passed via ``edit_url``
and ``delete_url`` kwargs at construction time. When used inside a
:class:`~ferrosoft.apps.ferrobase.tables.WidgetColumn` the column
monkey-patches ``render_args`` and ``render_kwargs`` onto the widget
instance so the callables receive the row record; either callable may
be ``None`` to suppress that button.
"""
template_name = "emiflow/treatmentoperation/line_actions_widget.html"
def __init__(self, *args, **kwargs):
"""Capture optional ``edit_url`` and ``delete_url`` URL-builder callables."""
self._edit_url = kwargs.pop("edit_url", None)
self._delete_url = kwargs.pop("delete_url", None)
super().__init__(*args, **kwargs)
[docs]
def get_context(self, *args, **kwargs):
"""Resolve ``edit_url`` and ``delete_url`` for the current row and inject them."""
# These are properties monkey patched by WidgetColumn.
url_args = args + getattr(self, "render_args", ())
url_kwargs = kwargs | getattr(self, "render_kwargs", {})
edit_url = None if self._edit_url is None else self._edit_url(
*url_args, **url_kwargs,
)
delete_url = None if self._delete_url is None else self._delete_url(
*url_args, **url_kwargs,
)
return super().get_context(*args, **kwargs) | {
"edit_url": edit_url,
"delete_url": delete_url,
}