Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

parentadmin.py 15KB

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