Skip to content

Handlers

Warning

This is an internal API and should be used only for extend/customise core behaviours.

classDiagram
    BaseExtraHandler <-- ViewHandler
    ButtonMixin <-- ButtonHandler
    ViewHandler <-- ButtonHandler

    ButtonMixin <-- LinkHandler
    BaseExtraHandler <-- LinkHandler

    LinkHandler <-- ChoiceHandler

    Button <-- LinkButton
    LinkButton <-- ChoiceButton

admin_extra_buttons.handlers.BaseExtraHandler

Source code in src/admin_extra_buttons/handlers.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class BaseExtraHandler:
    def __init__(self, func: HandlerFunction, **kwargs: Any) -> None:
        self.func: HandlerFunction = func
        self.url_name: str = ""
        self.func.extra_buttons_handler = self
        self.config = kwargs
        self.model_admin: "ExtraButtonsMixin" = kwargs.get("model_admin")  # type:ignore[assignment]
        self.decorators = kwargs.get("decorators", [])
        self.login_required = kwargs.get("login_required", True)
        self._pattern = kwargs.get("pattern", "") or ""
        self.permission: str | PermissionHandler | None = kwargs.get("permission")
        self._sig: inspect.Signature = inspect.signature(self.func)

    @cached_property
    def func_args(self) -> list[Any]:
        return list(self._sig.parameters)

    @cached_property
    def single_object_invocation(self) -> bool:
        return len(self.func_args) == 2  # noqa: PLR2004

    def __repr__(self) -> str:
        return f"<{self.__class__.__name__} {self.name}>"

    def get_instance(self, model_admin: "ExtraButtonsMixin") -> "BaseExtraHandler":
        """return a 'clone' of current Handler"""
        return self.__class__(self.func, model_admin=model_admin, **self.config)

    @cached_property
    def name(self) -> str:
        return self.func.__name__

    def __call__(
        self, model_admin: "ExtraButtonsMixin", request: HttpRequest, *args: Any, **kwargs: Any
    ) -> HttpResponseBase:
        obj = None
        self.model_admin = model_admin
        if not self.single_object_invocation:
            pk = str(kwargs.get(self.func_args[2]))
            obj = model_admin.get_object(request, pk)

        if self.permission:
            check_permission(self, self.permission, request, obj)
        elif self.login_required and not request.user.is_authenticated:
            raise PermissionDenied

        ret = self.func(model_admin, request, *args, **kwargs)

        if not isinstance(ret, HttpResponseBase):
            return HttpResponseRedirectToReferrer(request)
        return ret

admin_extra_buttons.handlers.ViewHandler

Bases: BaseExtraHandler

Source code in src/admin_extra_buttons/handlers.py
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
class ViewHandler(BaseExtraHandler):
    def __init__(
        self,
        func: "HandlerFunction",
        http_basic_auth: bool = False,
        http_auth_handler: Callable[[HttpRequest], AbstractBaseUser | AnonymousUser | None] | None = None,
        **kwargs: Any,
    ) -> None:
        if http_auth_handler:
            if http_basic_auth:
                raise ValueError("'http_basic_auth' and 'http_auth_handler' are mutually exclusive")
            self.http_auth_handler = http_auth_handler
            self.http_basic_auth = True
        else:
            self.http_basic_auth = http_basic_auth
            self.http_auth_handler = handle_basic_auth
        super().__init__(func, **kwargs)

    def __call__(
        self, model_admin: "ExtraButtonsMixin", request: HttpRequest, *args: Any, **kwargs: Any
    ) -> HttpResponseBase:
        self.model_admin = model_admin
        if self.login_required and self.http_basic_auth and not request.user.is_authenticated:
            self.http_auth_handler(request)
        return super().__call__(model_admin, request, *args, **kwargs)

    @cached_property
    def url_pattern(self) -> str:
        if self._pattern:
            return self._pattern
        pattern = ""
        for arg in list(self.func_args)[2:]:
            pattern += f"<path:{arg}>/"
        pattern += f"{self.name}/"
        return pattern

admin_extra_buttons.handlers.ButtonHandler

Bases: ButtonMixin, ViewHandler

View handler for @button decorated views

Source code in src/admin_extra_buttons/handlers.py
160
161
162
163
164
165
166
167
168
169
170
171
class ButtonHandler(ButtonMixin, ViewHandler):
    """View handler for `@button` decorated views"""

    button_class = ButtonWidget

    def get_button_params(self, context: RequestContext, **extra: Any) -> dict[str, Any]:
        return super().get_button_params(
            context,
            label=self.config.get("label", labelize(self.name)),
            login_required=self.login_required,
            **extra,
        )

admin_extra_buttons.handlers.LinkHandler

Bases: ButtonMixin, BaseExtraHandler

Source code in src/admin_extra_buttons/handlers.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
class LinkHandler(ButtonMixin, BaseExtraHandler):
    button_class: "type[VisibleButton]" = LinkButton
    url_pattern = None

    def __init__(self, func: HandlerFunction, **kwargs: Any) -> None:
        self.href = kwargs.pop("href", None)
        super().__init__(func, href=self.href, **kwargs)

    def get_button_params(self, context: RequestContext, **extra: Any) -> dict[str, Any]:
        return super().get_button_params(
            context,
            href=self.href,
            url_pattern=self.url_pattern,
            **extra,
        )

    def get_button(self, context: "RequestContext") -> "ButtonWidget":
        params = self.get_button_params(context)
        button = self.button_class(**params)
        self.func(self.model_admin, button)
        return button

admin_extra_buttons.handlers.ChoiceHandler

Bases: LinkHandler

Source code in src/admin_extra_buttons/handlers.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
class ChoiceHandler(LinkHandler):
    button_class: "type[VisibleButton]" = ChoiceButton

    def __init__(self, func: "HandlerFunction", **kwargs: Any) -> None:
        self.href = kwargs.pop("href", None)
        self.choices = kwargs.pop("choices", None)
        self.selected_choice = None
        super().__init__(func, href=self.href, choices=self.choices, **kwargs)

    def get_button_params(self, context: RequestContext, **extra: Any) -> dict[str, Any]:
        return super().get_button_params(
            context,
            choices=self.choices,
            **extra,
        )

admin_extra_buttons.handlers.ButtonMixin

Source code in src/admin_extra_buttons/handlers.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
class ButtonMixin:
    button_class: "type[VisibleButton]" = ButtonWidget

    def __init__(
        self,
        func: "HandlerFunction",
        html_attrs: dict[str, str] | None = None,
        change_list: bool | None = None,
        change_form: bool | None = None,
        visible: bool = True,
        enabled: bool = True,
        **kwargs: Any,
    ) -> None:
        self.config = kwargs
        self.change_form = change_form
        self.change_list = change_list
        self.visible = visible
        self.enabled = enabled
        self.html_attrs = html_attrs or {}

        super().__init__(  # type:ignore[call-arg]
            func,
            change_form=change_form,
            change_list=change_list,
            html_attrs=html_attrs,
            enabled=enabled,
            visible=visible,
            **kwargs,
        )

    def get_button_params(self, context: "RequestContext", **extra: Any) -> dict[str, Any]:
        return {
            "handler": self,
            "html_attrs": self.html_attrs,
            "change_list": self.change_list,
            "change_form": self.change_form,
            "visible": self.visible,
            "enabled": self.enabled,
            "context": context,
            **extra,
        }

    def get_button(self, context: "RequestContext") -> "ButtonWidget":
        return self.button_class(**self.get_button_params(context))

admin_extra_buttons.buttons.LinkButton

Bases: ButtonWidget

Source code in src/admin_extra_buttons/buttons.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
class LinkButton(ButtonWidget):
    @property
    def url(self) -> str:
        return self.href

    def get_change_form_flag(self, arg: Any | None) -> bool:  # noqa: PLR6301
        if arg is None:
            return True
        return bool(arg)

    def get_change_list_flag(self, arg: Any | None) -> bool:  # noqa: PLR6301
        if arg is None:
            return True
        return bool(arg)

admin_extra_buttons.buttons.ChoiceButton

Bases: LinkButton

Source code in src/admin_extra_buttons/buttons.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
class ChoiceButton(LinkButton):
    default_template = "admin_extra_buttons/includes/choice.html"

    def __init__(  # noqa: PLR0917, PLR0913
        self,
        handler: "BaseExtraHandler",
        context: "RequestContext",
        label: str | None = None,
        visible: bool = True,
        enabled: bool = True,
        change_form: bool | None = None,
        change_list: bool | None = None,
        template: str | None = None,
        **config: Any,
    ) -> None:
        self.choices: list[BaseExtraHandler] = []
        super().__init__(handler, context, label, visible, enabled, change_form, change_list, template, **config)

    def get_choices(self) -> Generator[dict[str, Any], None, None]:
        for handler_config in self.choices:
            handler = handler_config.func.extra_buttons_handler
            if self.change_list and handler.single_object_invocation:
                url = reverse(f"admin:{handler.url_name}")
            elif not handler.single_object_invocation and self.change_form and self.original:
                url = reverse(f"admin:{handler.url_name}", args=[self.context["original"].pk])
            else:
                url = None
            if url:
                yield {
                    "label": handler.config.get("label", labelize(handler.name)),
                    "url": url,
                    "selected": self.request.path == url,
                }
        yield {}

    def can_render(self) -> bool:  # noqa: PLR6301
        return True

    @property
    def html_attrs(self) -> dict[str, str]:
        ret = super().html_attrs
        ret.setdefault("name", self.handler.name)
        return ret