Debian Codegraph @

src/polymorphic/admin/inlines.py

raw
1 """
2 Django Admin support for polymorphic inlines.
3
4 Each row in the inline can correspond with a different subclass.
5 """
6
7 from __future__ import annotations
8
9 from functools import partial
10 from typing import TYPE_CHECKING, Any, cast
11
12 from django.conf import settings
13 from django.contrib.admin.options import InlineModelAdmin
14 from django.contrib.admin.sites import AdminSite
15 from django.contrib.admin.utils import flatten_fieldsets
16 from django.core.exceptions import ImproperlyConfigured
17 from django.db import models
18 from django.forms import Media
19 from django.http import HttpRequest
20
21 from polymorphic.formsets import (
22 BasePolymorphicInlineFormSet,
23 PolymorphicFormSetChild,
24 UnsupportedChildType,
25 polymorphic_child_forms_factory,
26 )
27 from polymorphic.formsets.utils import add_media
28
29 from .helpers import PolymorphicInlineSupportMixin
30
31 if TYPE_CHECKING:
32 from django.contrib.admin.options import _FieldGroups, _FieldsetSpec
33
34
35 class PolymorphicInlineModelAdmin(InlineModelAdmin):
36 """
37 A polymorphic inline, where each formset row can be a different form.
38
39 Note that:
40
41 * Permissions are only checked on the base model.
42 * The child inlines can't override the base model fields, only this parent inline can do that.
43 """
44
45 formset: type[BasePolymorphicInlineFormSet] = BasePolymorphicInlineFormSet
46
47 #: The extra media to add for the polymorphic inlines effect.
48 #: This can be redefined for subclasses.
49 polymorphic_media: Media = Media(
50 js=(
51 f"admin/js/vendor/jquery/{'jquery' if settings.DEBUG else 'jquery.min'}.js",
52 "admin/js/jquery.init.js",
53 "polymorphic/js/polymorphic_inlines.js",
54 ),
55 css={"all": ("polymorphic/css/polymorphic_inlines.css",)},
56 )
57
58 #: The extra forms to show
59 #: By default there are no 'extra' forms as the desired type is unknown.
60 #: Instead, add each new item using JavaScript that first offers a type-selection.
61 extra: int = 0
62
63 #: Inlines for all model sub types that can be displayed in this inline.
64 #: Each row is a :class:`PolymorphicInlineModelAdmin.Child`
65 child_inlines: list[type["PolymorphicInlineModelAdmin.Child"]] = []
66
67 child_inline_instances: list["PolymorphicInlineModelAdmin.Child"]
68
69 def __init__(self, parent_model: type[models.Model], admin_site: AdminSite) -> None:
70 super().__init__(parent_model, admin_site)
71
72 # Extra check to avoid confusion
73 # While we could monkeypatch the admin here, better stay explicit.
74 parent_admin = admin_site._registry.get(parent_model, None)
75 if parent_admin is not None: # Can be None during check
76 if not isinstance(parent_admin, PolymorphicInlineSupportMixin):
77 raise ImproperlyConfigured(
78 "To use polymorphic inlines, add the `PolymorphicInlineSupportMixin` mixin "
79 "to the ModelAdmin that hosts the inline."
80 )
81
82 # While the inline is created per request, the 'request' object is not known here.
83 # Hence, creating all child inlines unconditionally, without checking permissions.
84 self.child_inline_instances = self.get_child_inline_instances()
85
86 # Create a lookup table
87 self._child_inlines_lookup = {}
88 for child_inline in self.child_inline_instances:
89 self._child_inlines_lookup[child_inline.model] = child_inline
90
91 def get_child_inlines(self) -> list[type["PolymorphicInlineModelAdmin.Child"]]:
92 """
93 Return the derived inline classes which this admin should handle.
94
95 This should return an iterable of
96 :class:`~polymorphic.admin.inlines.PolymorphicInlineModelAdmin.Child` classes,
97 to override :attr:`~polymorphic.admin.inlines.PolymorphicInlineModelAdmin.child_inlines`.
98 """
99 return self.child_inlines or []
100
101 def get_child_inline_instances(self) -> list["PolymorphicInlineModelAdmin.Child"]:
102 """
103 :rtype List[PolymorphicInlineModelAdmin.Child]
104 """
105 instances = []
106 for ChildInlineType in self.get_child_inlines():
107 instances.append(ChildInlineType(parent_inline=self))
108 return instances
109
110 def get_child_inline_instance(
111 self, model: type[models.Model]
112 ) -> "PolymorphicInlineModelAdmin.Child":
113 """
114 Find the child inline for a given model.
115
116 :rtype: PolymorphicInlineModelAdmin.Child
117 """
118 try:
119 return self._child_inlines_lookup[model]
120 except KeyError:
121 raise UnsupportedChildType(f"Model '{model.__name__}' not found in child_inlines")
122
123 def get_formset(
124 self, request: HttpRequest, obj: Any = None, **kwargs: Any
125 ) -> type[BasePolymorphicInlineFormSet]:
126 """
127 Construct the inline formset class.
128
129 This passes all class attributes to the formset.
130
131 :rtype: type
132 """
133 # Construct the FormSet class
134 FormSet = super().get_formset(request, obj=obj, **kwargs)
135
136 # Instead of completely redefining super().get_formset(), we use
137 # the regular inlineformset_factory(), and amend that with our extra bits.
138 # This code line is the essence of what polymorphic_inlineformset_factory() does.
139 FormSet.child_forms = polymorphic_child_forms_factory( # type: ignore[attr-defined]
140 formset_children=self.get_formset_children(request, obj=obj)
141 )
142 return cast(type[BasePolymorphicInlineFormSet], FormSet)
143
144 def get_formset_children(
145 self, request: HttpRequest, obj: Any = None
146 ) -> list[PolymorphicFormSetChild]:
147 """
148 The formset 'children' provide the details for all child models that are part of this formset.
149 It provides a stripped version of the modelform/formset factory methods.
150 """
151 formset_children = []
152 for child_inline in self.child_inline_instances:
153 # TODO: the children can be limited here per request based on permissions.
154 formset_children.append(child_inline.get_formset_child(request, obj=obj))
155 return formset_children
156
157 def get_fieldsets(self, request: HttpRequest, obj: Any = None) -> "_FieldsetSpec":
158 """
159 Hook for specifying fieldsets.
160 """
161 if self.fieldsets:
162 return self.fieldsets
163 else:
164 return [] # Avoid exposing fields to the child
165
166 def get_fields(self, request: HttpRequest, obj: Any = None) -> "_FieldGroups":
167 if self.fields:
168 # Django's stubs type fields as Sequence[str | Sequence[str]]
169 return self.fields
170 else:
171 return [] # Avoid exposing fields to the child
172
173 @property
174 def media(self):
175 # The media of the inline focuses on the admin settings,
176 # whether to expose the scripts for filter_horizontal etc..
177 # The admin helper exposes the inline + formset media.
178 base_media = super().media
179 all_media = Media()
180 add_media(all_media, base_media)
181
182 # Add all media of the child inline instances
183 for child_instance in self.child_inline_instances:
184 child_media = child_instance.media
185
186 # Avoid adding the same media object again and again
187 if child_media._css != base_media._css and child_media._js != base_media._js: # type: ignore[attr-defined]
188 add_media(all_media, child_media)
189
190 add_media(all_media, self.polymorphic_media)
191
192 return all_media
193
194 class Child(InlineModelAdmin):
195 """
196 The child inline; which allows configuring the admin options
197 for the child appearance.
198
199 Note that not all options will be honored by the parent, notably the formset options:
200 * :attr:`extra`
201 * :attr:`min_num`
202 * :attr:`max_num`
203
204 The model form options however, will all be read.
205 """
206
207 formset_child: type[PolymorphicFormSetChild] = PolymorphicFormSetChild
208 extra: int = 0 # TODO: currently unused for the children.
209 parent_inline: "PolymorphicInlineModelAdmin"
210
211 def __init__(self, parent_inline: "PolymorphicInlineModelAdmin") -> None:
212 self.parent_inline = parent_inline
213 super(PolymorphicInlineModelAdmin.Child, self).__init__(
214 parent_inline.parent_model, parent_inline.admin_site
215 )
216
217 def get_formset(self, request: HttpRequest, obj: Any = None, **kwargs: Any) -> None: # type: ignore[override]
218 # The child inline is only used to construct the form,
219 # and allow to override the form field attributes.
220 # The formset is created by the parent inline.
221 raise RuntimeError("The child get_formset() is not used.")
222
223 def get_fields(self, request: HttpRequest, obj: Any = None) -> "_FieldGroups":
224 if self.fields:
225 return self.fields
226
227 # Standard Django logic, use the form to determine the fields.
228 # The form needs to pass through all factory logic so all 'excludes' are set as well.
229 # Default Django does: form = self.get_formset(request, obj, fields=None).form
230 # Use 'fields=None' avoids recursion in the field autodetection.
231 form = self.get_formset_child(request, obj, fields=None).get_form()
232 # Cast list[str] to _FieldGroups (compatible at runtime)
233 return cast(
234 "_FieldGroups",
235 list(form.base_fields) + list(self.get_readonly_fields(request, obj)),
236 )
237
238 def get_formset_child(
239 self, request: HttpRequest, obj: Any = None, **kwargs: Any
240 ) -> PolymorphicFormSetChild:
241 """
242 Return the formset child that the parent inline can use to represent us.
243
244 :rtype: PolymorphicFormSetChild
245 """
246 # Similar to the normal get_formset(), the caller may pass fields to override the defaults settings
247 # in the inline. In Django's GenericInlineModelAdmin.get_formset() this is also used in the same way,
248 # to make sure the 'exclude' also contains the GFK fields.
249 #
250 # Hence this code is almost identical to InlineModelAdmin.get_formset()
251 # and GenericInlineModelAdmin.get_formset()
252 #
253 # Transfer the local inline attributes to the formset child,
254 # this allows overriding settings.
255 if "fields" in kwargs:
256 fields = kwargs.pop("fields")
257 else:
258 fields = flatten_fieldsets(self.get_fieldsets(request, obj))
259
260 if self.exclude is None:
261 exclude = []
262 else:
263 exclude = list(self.exclude)
264
265 exclude.extend(self.get_readonly_fields(request, obj))
266 # Add forcefully, as Django 1.10 doesn't include readonly fields.
267 exclude.append("polymorphic_ctype")
268
269 if self.exclude is None and hasattr(self.form, "_meta") and self.form._meta.exclude:
270 # Take the custom ModelForm's Meta.exclude into account only if the
271 # InlineModelAdmin doesn't define its own.
272 exclude.extend(self.form._meta.exclude)
273
274 # can_delete = self.can_delete and self.has_delete_permission(request, obj)
275 defaults = {
276 "form": self.form,
277 "fields": fields,
278 "exclude": exclude or None,
279 "formfield_callback": partial(self.formfield_for_dbfield, request=request),
280 }
281 defaults.update(kwargs)
282
283 # This goes through the same logic that get_formset() calls
284 # by passing the inline class attributes to modelform_factory()
285 FormSetChildClass = self.formset_child
286 return FormSetChildClass(self.model, **defaults)
287
288
289 class StackedPolymorphicInline(PolymorphicInlineModelAdmin):
290 """
291 Stacked inline for django-polymorphic models.
292 Since tabular doesn't make much sense with changed fields, just offer this one.
293 """
294
295 #: The default template to use.
296 template: str = "admin/polymorphic/edit_inline/stacked.html"