| 1 |
""" |
| 2 |
The parent admin displays the list view of the base model. |
| 3 |
""" |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
from typing import TYPE_CHECKING, Any, Generic, cast |
| 8 |
|
| 9 |
from django.contrib import admin |
| 10 |
from django.contrib.admin.helpers import AdminErrorList, AdminForm |
| 11 |
from django.contrib.admin.templatetags.admin_urls import add_preserved_filters |
| 12 |
from django.contrib.contenttypes.models import ContentType |
| 13 |
from django.core.exceptions import ImproperlyConfigured, PermissionDenied |
| 14 |
from django.db import models |
| 15 |
from django.http import Http404, HttpResponseRedirect |
| 16 |
from django.template.response import TemplateResponse |
| 17 |
from django.utils.encoding import force_str |
| 18 |
from django.utils.translation import gettext_lazy as _ |
| 19 |
from typing_extensions import TypeVar |
| 20 |
|
| 21 |
from polymorphic.models import PolymorphicModel |
| 22 |
from polymorphic.query import PolymorphicQuerySet |
| 23 |
from polymorphic.utils import get_base_polymorphic_model |
| 24 |
|
| 25 |
from .forms import PolymorphicModelChoiceForm |
| 26 |
|
| 27 |
_ModelT = TypeVar("_ModelT", bound=PolymorphicModel, default=PolymorphicModel) |
| 28 |
|
| 29 |
if TYPE_CHECKING: |
| 30 |
_ModelAdminBase = admin.ModelAdmin[_ModelT] |
| 31 |
else: |
| 32 |
_ModelAdminBase = admin.ModelAdmin |
| 33 |
|
| 34 |
|
| 35 |
class RegistrationClosed(RuntimeError): |
| 36 |
"The admin model can't be registered anymore at this point." |
| 37 |
|
| 38 |
|
| 39 |
class ChildAdminNotRegistered(RuntimeError): |
| 40 |
"The admin site for the model is not registered." |
| 41 |
|
| 42 |
|
| 43 |
class PolymorphicParentModelAdmin(_ModelAdminBase, Generic[_ModelT]): |
| 44 |
""" |
| 45 |
A admin interface that can displays different change/delete pages, depending on the polymorphic model. |
| 46 |
To use this class, one attribute need to be defined: |
| 47 |
|
| 48 |
* :attr:`child_models` should be a list models. |
| 49 |
|
| 50 |
Alternatively, the following methods can be implemented: |
| 51 |
|
| 52 |
* :func:`get_child_models` should return a list of models. |
| 53 |
* optionally, :func:`get_child_type_choices` can be overwritten to refine the choices for the add dialog. |
| 54 |
|
| 55 |
This class needs to be inherited by the model admin base class that is registered in the site. |
| 56 |
The derived models should *not* register the ModelAdmin, but instead it should be returned by :func:`get_child_models`. |
| 57 |
""" |
| 58 |
|
| 59 |
#: The base model that the class uses (auto-detected if not set explicitly) |
| 60 |
base_model: type[models.Model] | None = None |
| 61 |
|
| 62 |
#: The child models that should be displayed |
| 63 |
child_models: list[type[models.Model]] | None = None |
| 64 |
|
| 65 |
#: Whether the list should be polymorphic too, leave to ``False`` to optimize |
| 66 |
polymorphic_list = False |
| 67 |
|
| 68 |
add_type_template = None |
| 69 |
add_type_form = PolymorphicModelChoiceForm |
| 70 |
|
| 71 |
#: The regular expression to filter the primary key in the URL. |
| 72 |
#: This accepts only numbers as defensive measure against catch-all URLs. |
| 73 |
#: If your primary key consists of string values, update this regular expression. |
| 74 |
pk_regex = r"(\d+|__fk__)" |
| 75 |
|
| 76 |
def __init__(self, model: type[_ModelT], admin_site: Any, *args: Any, **kwargs: Any) -> None: |
| 77 |
super().__init__(model, admin_site, *args, **kwargs) |
| 78 |
self._is_setup = False |
| 79 |
|
| 80 |
if self.base_model is None: |
| 81 |
self.base_model = get_base_polymorphic_model(model) |
| 82 |
|
| 83 |
def _lazy_setup(self): |
| 84 |
if self._is_setup: |
| 85 |
return |
| 86 |
|
| 87 |
self._child_models = self.get_child_models() |
| 88 |
|
| 89 |
# Make absolutely sure that the child models don't use the old 0.9 format, |
| 90 |
# as of polymorphic 1.4 this deprecated configuration is no longer supported. |
| 91 |
# Instead, register the child models in the admin too. |
| 92 |
if self._child_models and not issubclass(self._child_models[0], models.Model): |
| 93 |
raise ImproperlyConfigured( |
| 94 |
"Since django-polymorphic 1.4, the `child_models` attribute " |
| 95 |
"and `get_child_models()` method should be a list of models only.\n" |
| 96 |
"The model-admin class should be registered in the regular Django admin." |
| 97 |
) |
| 98 |
|
| 99 |
self._child_admin_site = self.admin_site |
| 100 |
self._is_setup = True |
| 101 |
|
| 102 |
def get_child_models(self): |
| 103 |
""" |
| 104 |
Return the derived model classes which this admin should handle. |
| 105 |
This should return a list of tuples, exactly like :attr:`child_models` is. |
| 106 |
|
| 107 |
The model classes can be retrieved as ``base_model.__subclasses__()``, |
| 108 |
a setting in a config file, or a query of a plugin registration system at your option |
| 109 |
""" |
| 110 |
if self.child_models is None: |
| 111 |
raise NotImplementedError("Implement get_child_models() or child_models") |
| 112 |
|
| 113 |
return self.child_models |
| 114 |
|
| 115 |
def get_child_type_choices(self, request, action): |
| 116 |
""" |
| 117 |
Return a list of polymorphic types for which the user has the permission to perform the given action. |
| 118 |
""" |
| 119 |
self._lazy_setup() |
| 120 |
choices = [] |
| 121 |
content_types = ContentType.objects.get_for_models( |
| 122 |
*self.get_child_models(), for_concrete_models=False |
| 123 |
) |
| 124 |
|
| 125 |
for model, ct in content_types.items(): |
| 126 |
perm_function_name = f"has_{action}_permission" |
| 127 |
model_admin = self._get_real_admin_by_model(model) |
| 128 |
perm_function = getattr(model_admin, perm_function_name) |
| 129 |
if not perm_function(request): |
| 130 |
continue |
| 131 |
choices.append((ct.id, model._meta.verbose_name)) |
| 132 |
return choices |
| 133 |
|
| 134 |
def _get_real_admin(self, object_id, super_if_self=True): |
| 135 |
try: |
| 136 |
obj = ( |
| 137 |
self.model.objects.non_polymorphic().values("polymorphic_ctype").get(pk=object_id) |
| 138 |
) |
| 139 |
except self.model.DoesNotExist: |
| 140 |
raise Http404 |
| 141 |
return self._get_real_admin_by_ct(obj["polymorphic_ctype"], super_if_self=super_if_self) |
| 142 |
|
| 143 |
def _get_real_admin_by_ct(self, ct_id, super_if_self=True): |
| 144 |
try: |
| 145 |
ct = ContentType.objects.get_for_id(ct_id) |
| 146 |
except ContentType.DoesNotExist as e: |
| 147 |
raise Http404(e) # Handle invalid GET parameters |
| 148 |
|
| 149 |
model_class = ct.model_class() |
| 150 |
if not model_class: |
| 151 |
# Handle model deletion |
| 152 |
app_label, model = ct.natural_key() |
| 153 |
raise Http404(f"No model found for '{app_label}.{model}'.") |
| 154 |
|
| 155 |
return self._get_real_admin_by_model(model_class, super_if_self=super_if_self) |
| 156 |
|
| 157 |
def _get_real_admin_by_model(self, model_class, super_if_self=True): |
| 158 |
# In case of a ?ct_id=### parameter, the view is already checked for permissions. |
| 159 |
# Hence, make sure this is a derived object, or risk exposing other admin interfaces. |
| 160 |
if model_class not in self._child_models: |
| 161 |
raise PermissionDenied( |
| 162 |
f"Invalid model '{model_class}', it must be registered as child model." |
| 163 |
) |
| 164 |
|
| 165 |
try: |
| 166 |
# HACK: the only way to get the instance of an model admin, |
| 167 |
# is to read the registry of the AdminSite. |
| 168 |
real_admin = self._child_admin_site._registry[model_class] |
| 169 |
except KeyError: |
| 170 |
raise ChildAdminNotRegistered( |
| 171 |
f"No child admin site was registered for a '{model_class}' model." |
| 172 |
) |
| 173 |
|
| 174 |
if super_if_self and real_admin is self: |
| 175 |
return super() |
| 176 |
else: |
| 177 |
return real_admin |
| 178 |
|
| 179 |
def get_queryset(self, request): |
| 180 |
# optimize the list display. |
| 181 |
qs = cast(PolymorphicQuerySet, super().get_queryset(request)) |
| 182 |
if not self.polymorphic_list: |
| 183 |
qs = qs.non_polymorphic() |
| 184 |
return qs |
| 185 |
|
| 186 |
def add_view(self, request, form_url="", extra_context=None): |
| 187 |
"""Redirect the add view to the real admin.""" |
| 188 |
ct_id = int(request.GET.get("ct_id", 0)) |
| 189 |
if not ct_id: |
| 190 |
# Display choices |
| 191 |
return self.add_type_view(request) |
| 192 |
else: |
| 193 |
real_admin = self._get_real_admin_by_ct(ct_id) |
| 194 |
# rebuild form_url, otherwise libraries below will override it. |
| 195 |
# Preserve popup-related parameters to ensure popup functionality works |
| 196 |
# correctly even after validation errors (issue #612) |
| 197 |
form_url = add_preserved_filters( |
| 198 |
{ |
| 199 |
"preserved_filters": request.GET.urlencode(), |
| 200 |
"opts": self.model._meta, |
| 201 |
}, |
| 202 |
form_url, |
| 203 |
) |
| 204 |
return real_admin.add_view(request, form_url, extra_context) |
| 205 |
|
| 206 |
def change_view(self, request, object_id, *args, **kwargs): |
| 207 |
"""Redirect the change view to the real admin.""" |
| 208 |
real_admin = self._get_real_admin(object_id) |
| 209 |
return real_admin.change_view(request, object_id, *args, **kwargs) |
| 210 |
|
| 211 |
def changeform_view(self, request, object_id=None, *args, **kwargs): |
| 212 |
# The `changeform_view` is available as of Django 1.7, combining the add_view and change_view. |
| 213 |
# As it's directly called by django-reversion, this method is also overwritten to make sure it |
| 214 |
# also redirects to the child admin. |
| 215 |
if object_id: |
| 216 |
real_admin = self._get_real_admin(object_id) |
| 217 |
return real_admin.changeform_view(request, object_id, *args, **kwargs) |
| 218 |
else: |
| 219 |
# Add view. As it should already be handled via `add_view`, this means something custom is done here! |
| 220 |
return super().changeform_view(request, object_id, *args, **kwargs) |
| 221 |
|
| 222 |
def history_view(self, request, object_id, extra_context=None): |
| 223 |
"""Redirect the history view to the real admin.""" |
| 224 |
real_admin = self._get_real_admin(object_id) |
| 225 |
return real_admin.history_view(request, object_id, extra_context=extra_context) |
| 226 |
|
| 227 |
def delete_view(self, request, object_id, extra_context=None): |
| 228 |
"""Redirect the delete view to the real admin.""" |
| 229 |
real_admin = self._get_real_admin(object_id) |
| 230 |
return real_admin.delete_view(request, object_id, extra_context) |
| 231 |
|
| 232 |
def get_urls(self): |
| 233 |
""" |
| 234 |
Expose the custom URLs for the subclasses and the URL resolver. |
| 235 |
""" |
| 236 |
urls = super().get_urls() |
| 237 |
|
| 238 |
# At this point. all admin code needs to be known. |
| 239 |
self._lazy_setup() |
| 240 |
|
| 241 |
return urls |
| 242 |
|
| 243 |
def add_type_view(self, request, form_url=""): |
| 244 |
""" |
| 245 |
Display a choice form to select which page type to add. |
| 246 |
""" |
| 247 |
if not self.has_add_permission(request): |
| 248 |
raise PermissionDenied |
| 249 |
|
| 250 |
extra_qs = "" |
| 251 |
if request.META["QUERY_STRING"]: |
| 252 |
# QUERY_STRING is bytes in Python 3, using force_str() to decode it as string. |
| 253 |
# See QueryDict how Django deals with that. |
| 254 |
# TODO: should this use a Django method instead of manipulating the string directly? |
| 255 |
extra_qs = f"&{force_str(request.META['QUERY_STRING'])}" |
| 256 |
|
| 257 |
choices = self.get_child_type_choices(request, "add") |
| 258 |
if len(choices) == 0: |
| 259 |
raise PermissionDenied |
| 260 |
if len(choices) == 1: |
| 261 |
return HttpResponseRedirect(f"?ct_id={choices[0][0]}{extra_qs}") |
| 262 |
|
| 263 |
# Create form |
| 264 |
form = self.add_type_form( |
| 265 |
data=request.POST if request.method == "POST" else None, |
| 266 |
initial={"ct_id": choices[0][0]}, |
| 267 |
) |
| 268 |
setattr(form.fields["ct_id"], "choices", choices) |
| 269 |
|
| 270 |
if form.is_valid(): |
| 271 |
return HttpResponseRedirect(f"?ct_id={form.cleaned_data['ct_id']}{extra_qs}") |
| 272 |
|
| 273 |
# Wrap in all admin layout |
| 274 |
fieldsets = ((None, {"fields": ("ct_id",)}),) |
| 275 |
adminForm = AdminForm(form, fieldsets, {}, model_admin=self) # type: ignore[arg-type] |
| 276 |
media = self.media + adminForm.media |
| 277 |
opts = self.model._meta |
| 278 |
|
| 279 |
context = { |
| 280 |
"title": _("Add %s") % force_str(opts.verbose_name), |
| 281 |
"adminform": adminForm, |
| 282 |
"is_popup": ("_popup" in request.POST or "_popup" in request.GET), |
| 283 |
"media": media, |
| 284 |
"errors": AdminErrorList(form, ()), # type: ignore[arg-type] |
| 285 |
"app_label": opts.app_label, |
| 286 |
} |
| 287 |
return self.render_add_type_form(request, context, form_url) |
| 288 |
|
| 289 |
def render_add_type_form(self, request, context, form_url=""): |
| 290 |
""" |
| 291 |
Render the page type choice form. |
| 292 |
""" |
| 293 |
opts = self.model._meta |
| 294 |
app_label = opts.app_label |
| 295 |
context.update( |
| 296 |
{ |
| 297 |
"has_change_permission": self.has_change_permission(request), |
| 298 |
"form_url": form_url, |
| 299 |
"opts": opts, |
| 300 |
"add": True, |
| 301 |
"save_on_top": self.save_on_top, |
| 302 |
**self.admin_site.each_context(request), |
| 303 |
} |
| 304 |
) |
| 305 |
|
| 306 |
templates = self.add_type_template or [ |
| 307 |
f"admin/{app_label}/{opts.object_name.lower()}/add_type_form.html", # type: ignore[union-attr] |
| 308 |
f"admin/{app_label}/add_type_form.html", |
| 309 |
"admin/polymorphic/add_type_form.html", # added default here |
| 310 |
"admin/add_type_form.html", |
| 311 |
] |
| 312 |
|
| 313 |
request.current_app = self.admin_site.name |
| 314 |
return self.admin_site.admin_view(TemplateResponse)(request, templates, context) |
| 315 |
|
| 316 |
@property |
| 317 |
def change_list_template(self) -> list[str]: # type: ignore[override] |
| 318 |
opts = self.model._meta |
| 319 |
app_label = opts.app_label |
| 320 |
|
| 321 |
# Pass the base options |
| 322 |
assert self.base_model is not None, "base_model must be set" |
| 323 |
base_opts = self.base_model._meta |
| 324 |
base_app_label = base_opts.app_label |
| 325 |
|
| 326 |
return [ |
| 327 |
f"admin/{app_label}/{opts.object_name.lower()}/change_list.html", # type: ignore[union-attr] |
| 328 |
f"admin/{app_label}/change_list.html", |
| 329 |
# Added base class: |
| 330 |
f"admin/{base_app_label}/{base_opts.object_name.lower()}/change_list.html", # type: ignore[union-attr] |
| 331 |
f"admin/{base_app_label}/change_list.html", |
| 332 |
"admin/change_list.html", |
| 333 |
] |