| 1 |
""" |
| 2 |
The child admin displays the change/delete view of the subclass model. |
| 3 |
""" |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import inspect |
| 8 |
from typing import TYPE_CHECKING, Any, Generic |
| 9 |
|
| 10 |
from django.contrib import admin |
| 11 |
from django.db import models |
| 12 |
from django.forms import ModelForm |
| 13 |
from django.http import HttpRequest |
| 14 |
from django.urls import resolve |
| 15 |
from django.utils.translation import gettext_lazy as _ |
| 16 |
from typing_extensions import TypeVar |
| 17 |
|
| 18 |
from polymorphic.models import PolymorphicModel |
| 19 |
from polymorphic.utils import get_base_polymorphic_model |
| 20 |
|
| 21 |
from ..admin import PolymorphicParentModelAdmin |
| 22 |
|
| 23 |
_ModelT = TypeVar("_ModelT", bound=PolymorphicModel, default=PolymorphicModel) |
| 24 |
|
| 25 |
if TYPE_CHECKING: |
| 26 |
_ModelAdminBase = admin.ModelAdmin[_ModelT] |
| 27 |
else: |
| 28 |
_ModelAdminBase = admin.ModelAdmin |
| 29 |
|
| 30 |
|
| 31 |
class ParentAdminNotRegistered(RuntimeError): |
| 32 |
"The admin site for the model is not registered." |
| 33 |
|
| 34 |
|
| 35 |
class PolymorphicChildModelAdmin(_ModelAdminBase, Generic[_ModelT]): |
| 36 |
""" |
| 37 |
The *optional* base class for the admin interface of derived models. |
| 38 |
|
| 39 |
This base class defines some convenience behavior for the admin interface: |
| 40 |
|
| 41 |
* It corrects the breadcrumbs in the admin pages. |
| 42 |
* It adds the base model to the template lookup paths. |
| 43 |
* It allows to set ``base_form`` so the derived class will automatically include other fields in the form. |
| 44 |
* It allows to set ``base_fieldsets`` so the derived class will automatically display any extra fields. |
| 45 |
""" |
| 46 |
|
| 47 |
#: The base model that the class uses (auto-detected if not set explicitly) |
| 48 |
base_model: type[models.Model] | None = None |
| 49 |
|
| 50 |
#: By setting ``base_form`` instead of ``form``, any subclass fields are automatically added to the form. |
| 51 |
#: This is useful when your model admin class is inherited by others. |
| 52 |
base_form: type[ModelForm[Any]] | None = None |
| 53 |
|
| 54 |
#: By setting ``base_fieldsets`` instead of ``fieldsets``, |
| 55 |
#: any subclass fields can be automatically added. |
| 56 |
#: This is useful when your model admin class is inherited by others. |
| 57 |
base_fieldsets: Any = None |
| 58 |
|
| 59 |
#: Default title for extra fieldset |
| 60 |
extra_fieldset_title = _("Contents") |
| 61 |
|
| 62 |
#: Whether the child admin model should be visible in the admin index page. |
| 63 |
show_in_index = False |
| 64 |
|
| 65 |
def __init__(self, model: type[_ModelT], admin_site: Any, *args: Any, **kwargs: Any) -> None: |
| 66 |
super().__init__(model, admin_site, *args, **kwargs) |
| 67 |
|
| 68 |
if self.base_model is None: |
| 69 |
self.base_model = get_base_polymorphic_model(model) |
| 70 |
|
| 71 |
def get_form( |
| 72 |
self, request: HttpRequest, obj: Any | None = None, change: bool = False, **kwargs: Any |
| 73 |
) -> type[ModelForm[Any]]: |
| 74 |
# The django admin validation requires the form to have a 'class Meta: model = ..' |
| 75 |
# attribute, or it will complain that the fields are missing. |
| 76 |
# However, this enforces all derived ModelAdmin classes to redefine the model as well, |
| 77 |
# because they need to explicitly set the model again - it will stick with the base model. |
| 78 |
# |
| 79 |
# Instead, pass the form unchecked here, because the standard ModelForm will just work. |
| 80 |
# If the derived class sets the model explicitly, respect that setting. |
| 81 |
kwargs.setdefault("form", self.base_form or self.form) |
| 82 |
|
| 83 |
# prevent infinite recursion when this is called from get_subclass_fields |
| 84 |
if not self.fieldsets and not self.fields: |
| 85 |
kwargs.setdefault("fields", "__all__") |
| 86 |
|
| 87 |
return super().get_form(request, obj, **kwargs) |
| 88 |
|
| 89 |
def get_model_perms(self, request): |
| 90 |
match = resolve(request.path_info) |
| 91 |
|
| 92 |
if not self.show_in_index and match.namespace == self.admin_site.name: |
| 93 |
return {"add": False, "change": False, "delete": False} |
| 94 |
return super().get_model_perms(request) |
| 95 |
|
| 96 |
@property |
| 97 |
def change_form_template(self) -> list[str]: # type: ignore[override] |
| 98 |
opts = self.model._meta |
| 99 |
app_label = opts.app_label |
| 100 |
|
| 101 |
# Pass the base options |
| 102 |
assert self.base_model is not None, "base_model must be set" |
| 103 |
base_opts = self.base_model._meta |
| 104 |
base_app_label = base_opts.app_label |
| 105 |
|
| 106 |
return [ |
| 107 |
f"admin/{app_label}/{opts.object_name.lower()}/change_form.html", # type: ignore[union-attr] |
| 108 |
f"admin/{app_label}/change_form.html", |
| 109 |
# Added: |
| 110 |
f"admin/{base_app_label}/{base_opts.object_name.lower()}/change_form.html", # type: ignore[union-attr] |
| 111 |
f"admin/{base_app_label}/change_form.html", |
| 112 |
"admin/polymorphic/change_form.html", |
| 113 |
"admin/change_form.html", |
| 114 |
] |
| 115 |
|
| 116 |
@property |
| 117 |
def delete_confirmation_template(self) -> list[str]: # type: ignore[override] |
| 118 |
opts = self.model._meta |
| 119 |
app_label = opts.app_label |
| 120 |
|
| 121 |
# Pass the base options |
| 122 |
assert self.base_model is not None, "base_model must be set" |
| 123 |
base_opts = self.base_model._meta |
| 124 |
base_app_label = base_opts.app_label |
| 125 |
|
| 126 |
return [ |
| 127 |
f"admin/{app_label}/{opts.object_name.lower()}/delete_confirmation.html", # type: ignore[union-attr] |
| 128 |
f"admin/{app_label}/delete_confirmation.html", |
| 129 |
# Added: |
| 130 |
f"admin/{base_app_label}/{base_opts.object_name.lower()}/delete_confirmation.html", # type: ignore[union-attr] |
| 131 |
f"admin/{base_app_label}/delete_confirmation.html", |
| 132 |
"admin/polymorphic/delete_confirmation.html", |
| 133 |
"admin/delete_confirmation.html", |
| 134 |
] |
| 135 |
|
| 136 |
@property |
| 137 |
def object_history_template(self) -> list[str]: # type: ignore[override] |
| 138 |
opts = self.model._meta |
| 139 |
app_label = opts.app_label |
| 140 |
|
| 141 |
# Pass the base options |
| 142 |
assert self.base_model is not None, "base_model must be set" |
| 143 |
base_opts = self.base_model._meta |
| 144 |
base_app_label = base_opts.app_label |
| 145 |
|
| 146 |
return [ |
| 147 |
f"admin/{app_label}/{opts.object_name.lower()}/object_history.html", # type: ignore[union-attr] |
| 148 |
f"admin/{app_label}/object_history.html", |
| 149 |
# Added: |
| 150 |
f"admin/{base_app_label}/{base_opts.object_name.lower()}/object_history.html", # type: ignore[union-attr] |
| 151 |
f"admin/{base_app_label}/object_history.html", |
| 152 |
"admin/polymorphic/object_history.html", |
| 153 |
"admin/object_history.html", |
| 154 |
] |
| 155 |
|
| 156 |
def _get_parent_admin(self): |
| 157 |
# this returns parent admin instance on which to call response_post_save methods |
| 158 |
parent_model = self.model._meta.get_field("polymorphic_ctype").model |
| 159 |
if parent_model == self.model: |
| 160 |
# when parent_model is in among child_models, just return super instance |
| 161 |
return super() |
| 162 |
|
| 163 |
# Only PolymorphicParentModelAdmin registrations are considered, whether |
| 164 |
# they are for the polymorphic root model or an intermediate proxy/model |
| 165 |
# between the parent_model and this model. |
| 166 |
for klass in inspect.getmro(self.model): |
| 167 |
if not issubclass(klass, parent_model): |
| 168 |
continue # e.g. found a mixin. |
| 169 |
|
| 170 |
# Fetch admin instance for model class, see if it's a possible candidate. |
| 171 |
model_admin = self.admin_site._registry.get(klass) |
| 172 |
if model_admin is not None and isinstance(model_admin, PolymorphicParentModelAdmin): |
| 173 |
return model_admin # Success! |
| 174 |
|
| 175 |
# If we get this far without returning there is no admin available |
| 176 |
raise ParentAdminNotRegistered( |
| 177 |
f"No parent admin was registered for a '{parent_model}' model." |
| 178 |
) |
| 179 |
|
| 180 |
def response_post_save_add(self, request, obj): |
| 181 |
return self._get_parent_admin().response_post_save_add(request, obj) |
| 182 |
|
| 183 |
def response_post_save_change(self, request, obj): |
| 184 |
return self._get_parent_admin().response_post_save_change(request, obj) |
| 185 |
|
| 186 |
def render_change_form(self, request, context, add=False, change=False, form_url="", obj=None): |
| 187 |
assert self.base_model is not None, "base_model must be set" |
| 188 |
context.update({"base_opts": self.base_model._meta}) |
| 189 |
return super().render_change_form( |
| 190 |
request, context, add=add, change=change, form_url=form_url, obj=obj |
| 191 |
) |
| 192 |
|
| 193 |
def delete_view(self, request, object_id, context=None): |
| 194 |
assert self.base_model is not None, "base_model must be set" |
| 195 |
extra_context = {"base_opts": self.base_model._meta} |
| 196 |
return super().delete_view(request, object_id, extra_context) |
| 197 |
|
| 198 |
def history_view(self, request, object_id, extra_context=None): |
| 199 |
# Make sure the history view can also display polymorphic breadcrumbs |
| 200 |
assert self.base_model is not None, "base_model must be set" |
| 201 |
context = {"base_opts": self.base_model._meta} |
| 202 |
if extra_context: |
| 203 |
context.update(extra_context) |
| 204 |
return super().history_view(request, object_id, extra_context=context) |
| 205 |
|
| 206 |
# ---- Extra: improving the form/fieldset default display ---- |
| 207 |
|
| 208 |
def get_base_fieldsets(self, request, obj=None): |
| 209 |
return self.base_fieldsets |
| 210 |
|
| 211 |
def get_fieldsets(self, request, obj=None): |
| 212 |
base_fieldsets = self.get_base_fieldsets(request, obj) |
| 213 |
|
| 214 |
# If subclass declares fieldsets or fields, this is respected |
| 215 |
if self.fieldsets or self.fields or not self.base_fieldsets: |
| 216 |
return super().get_fieldsets(request, obj) |
| 217 |
|
| 218 |
# Have a reasonable default fieldsets, |
| 219 |
# where the subclass fields are automatically included. |
| 220 |
other_fields = self.get_subclass_fields(request, obj) |
| 221 |
|
| 222 |
if other_fields: |
| 223 |
return ( |
| 224 |
base_fieldsets[0], |
| 225 |
(self.extra_fieldset_title, {"fields": other_fields}), |
| 226 |
) + base_fieldsets[1:] |
| 227 |
else: |
| 228 |
return base_fieldsets |
| 229 |
|
| 230 |
def get_subclass_fields(self, request, obj=None): |
| 231 |
# Find out how many fields would really be on the form, |
| 232 |
# if it weren't restricted by declared fields. |
| 233 |
exclude = list(self.exclude or []) |
| 234 |
exclude.extend(self.get_readonly_fields(request, obj)) |
| 235 |
|
| 236 |
# By not declaring the fields/form in the base class, |
| 237 |
# get_form() will populate the form with all available fields. |
| 238 |
form = self.get_form(request, obj, exclude=exclude) |
| 239 |
subclass_fields = list(form.base_fields.keys()) + list( |
| 240 |
self.get_readonly_fields(request, obj) |
| 241 |
) |
| 242 |
|
| 243 |
# Find which fields are not part of the common fields. |
| 244 |
for fieldset in self.get_base_fieldsets(request, obj): |
| 245 |
for field in fieldset[1]["fields"]: |
| 246 |
# multiple elements in single line |
| 247 |
if isinstance(field, tuple): |
| 248 |
for line_field in field: |
| 249 |
try: |
| 250 |
subclass_fields.remove(line_field) |
| 251 |
except ValueError: |
| 252 |
pass # field not found in form, Django will raise exception later. |
| 253 |
else: |
| 254 |
# regular one-element-per-line |
| 255 |
try: |
| 256 |
subclass_fields.remove(field) |
| 257 |
except ValueError: |
| 258 |
pass # field not found in form, Django will raise exception later. |
| 259 |
return subclass_fields |