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.

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. import re
  2. from functools import update_wrapper
  3. from weakref import WeakSet
  4. from django.apps import apps
  5. from django.conf import settings
  6. from django.contrib.admin import ModelAdmin, actions
  7. from django.contrib.admin.views.autocomplete import AutocompleteJsonView
  8. from django.contrib.auth import REDIRECT_FIELD_NAME
  9. from django.core.exceptions import ImproperlyConfigured
  10. from django.db.models.base import ModelBase
  11. from django.http import Http404, HttpResponsePermanentRedirect, HttpResponseRedirect
  12. from django.template.response import TemplateResponse
  13. from django.urls import NoReverseMatch, Resolver404, resolve, reverse
  14. from django.utils.decorators import method_decorator
  15. from django.utils.functional import LazyObject
  16. from django.utils.module_loading import import_string
  17. from django.utils.text import capfirst
  18. from django.utils.translation import gettext as _
  19. from django.utils.translation import gettext_lazy
  20. from django.views.decorators.cache import never_cache
  21. from django.views.decorators.common import no_append_slash
  22. from django.views.decorators.csrf import csrf_protect
  23. from django.views.i18n import JavaScriptCatalog
  24. all_sites = WeakSet()
  25. class AlreadyRegistered(Exception):
  26. pass
  27. class NotRegistered(Exception):
  28. pass
  29. class AdminSite:
  30. """
  31. An AdminSite object encapsulates an instance of the Django admin application, ready
  32. to be hooked in to your URLconf. Models are registered with the AdminSite using the
  33. register() method, and the get_urls() method can then be used to access Django view
  34. functions that present a full admin interface for the collection of registered
  35. models.
  36. """
  37. # Text to put at the end of each page's <title>.
  38. site_title = gettext_lazy("Django site admin")
  39. # Text to put in each page's <h1>.
  40. site_header = gettext_lazy("Django administration")
  41. # Text to put at the top of the admin index page.
  42. index_title = gettext_lazy("Site administration")
  43. # URL for the "View site" link at the top of each admin page.
  44. site_url = "/"
  45. enable_nav_sidebar = True
  46. empty_value_display = "-"
  47. login_form = None
  48. index_template = None
  49. app_index_template = None
  50. login_template = None
  51. logout_template = None
  52. password_change_template = None
  53. password_change_done_template = None
  54. final_catch_all_view = True
  55. def __init__(self, name="admin"):
  56. self._registry = {} # model_class class -> admin_class instance
  57. self.name = name
  58. self._actions = {"delete_selected": actions.delete_selected}
  59. self._global_actions = self._actions.copy()
  60. all_sites.add(self)
  61. def __repr__(self):
  62. return f"{self.__class__.__name__}(name={self.name!r})"
  63. def check(self, app_configs):
  64. """
  65. Run the system checks on all ModelAdmins, except if they aren't
  66. customized at all.
  67. """
  68. if app_configs is None:
  69. app_configs = apps.get_app_configs()
  70. app_configs = set(app_configs) # Speed up lookups below
  71. errors = []
  72. modeladmins = (
  73. o for o in self._registry.values() if o.__class__ is not ModelAdmin
  74. )
  75. for modeladmin in modeladmins:
  76. if modeladmin.model._meta.app_config in app_configs:
  77. errors.extend(modeladmin.check())
  78. return errors
  79. def register(self, model_or_iterable, admin_class=None, **options):
  80. """
  81. Register the given model(s) with the given admin class.
  82. The model(s) should be Model classes, not instances.
  83. If an admin class isn't given, use ModelAdmin (the default admin
  84. options). If keyword arguments are given -- e.g., list_display --
  85. apply them as options to the admin class.
  86. If a model is already registered, raise AlreadyRegistered.
  87. If a model is abstract, raise ImproperlyConfigured.
  88. """
  89. admin_class = admin_class or ModelAdmin
  90. if isinstance(model_or_iterable, ModelBase):
  91. model_or_iterable = [model_or_iterable]
  92. for model in model_or_iterable:
  93. if model._meta.abstract:
  94. raise ImproperlyConfigured(
  95. "The model %s is abstract, so it cannot be registered with admin."
  96. % model.__name__
  97. )
  98. if model in self._registry:
  99. registered_admin = str(self._registry[model])
  100. msg = "The model %s is already registered " % model.__name__
  101. if registered_admin.endswith(".ModelAdmin"):
  102. # Most likely registered without a ModelAdmin subclass.
  103. msg += "in app %r." % re.sub(r"\.ModelAdmin$", "", registered_admin)
  104. else:
  105. msg += "with %r." % registered_admin
  106. raise AlreadyRegistered(msg)
  107. # Ignore the registration if the model has been
  108. # swapped out.
  109. if not model._meta.swapped:
  110. # If we got **options then dynamically construct a subclass of
  111. # admin_class with those **options.
  112. if options:
  113. # For reasons I don't quite understand, without a __module__
  114. # the created class appears to "live" in the wrong place,
  115. # which causes issues later on.
  116. options["__module__"] = __name__
  117. admin_class = type(
  118. "%sAdmin" % model.__name__, (admin_class,), options
  119. )
  120. # Instantiate the admin class to save in the registry
  121. self._registry[model] = admin_class(model, self)
  122. def unregister(self, model_or_iterable):
  123. """
  124. Unregister the given model(s).
  125. If a model isn't already registered, raise NotRegistered.
  126. """
  127. if isinstance(model_or_iterable, ModelBase):
  128. model_or_iterable = [model_or_iterable]
  129. for model in model_or_iterable:
  130. if model not in self._registry:
  131. raise NotRegistered("The model %s is not registered" % model.__name__)
  132. del self._registry[model]
  133. def is_registered(self, model):
  134. """
  135. Check if a model class is registered with this `AdminSite`.
  136. """
  137. return model in self._registry
  138. def add_action(self, action, name=None):
  139. """
  140. Register an action to be available globally.
  141. """
  142. name = name or action.__name__
  143. self._actions[name] = action
  144. self._global_actions[name] = action
  145. def disable_action(self, name):
  146. """
  147. Disable a globally-registered action. Raise KeyError for invalid names.
  148. """
  149. del self._actions[name]
  150. def get_action(self, name):
  151. """
  152. Explicitly get a registered global action whether it's enabled or
  153. not. Raise KeyError for invalid names.
  154. """
  155. return self._global_actions[name]
  156. @property
  157. def actions(self):
  158. """
  159. Get all the enabled actions as an iterable of (name, func).
  160. """
  161. return self._actions.items()
  162. def has_permission(self, request):
  163. """
  164. Return True if the given HttpRequest has permission to view
  165. *at least one* page in the admin site.
  166. """
  167. return request.user.is_active and request.user.is_staff
  168. def admin_view(self, view, cacheable=False):
  169. """
  170. Decorator to create an admin view attached to this ``AdminSite``. This
  171. wraps the view and provides permission checking by calling
  172. ``self.has_permission``.
  173. You'll want to use this from within ``AdminSite.get_urls()``:
  174. class MyAdminSite(AdminSite):
  175. def get_urls(self):
  176. from django.urls import path
  177. urls = super().get_urls()
  178. urls += [
  179. path('my_view/', self.admin_view(some_view))
  180. ]
  181. return urls
  182. By default, admin_views are marked non-cacheable using the
  183. ``never_cache`` decorator. If the view can be safely cached, set
  184. cacheable=True.
  185. """
  186. def inner(request, *args, **kwargs):
  187. if not self.has_permission(request):
  188. if request.path == reverse("admin:logout", current_app=self.name):
  189. index_path = reverse("admin:index", current_app=self.name)
  190. return HttpResponseRedirect(index_path)
  191. # Inner import to prevent django.contrib.admin (app) from
  192. # importing django.contrib.auth.models.User (unrelated model).
  193. from django.contrib.auth.views import redirect_to_login
  194. return redirect_to_login(
  195. request.get_full_path(),
  196. reverse("admin:login", current_app=self.name),
  197. )
  198. return view(request, *args, **kwargs)
  199. if not cacheable:
  200. inner = never_cache(inner)
  201. # We add csrf_protect here so this function can be used as a utility
  202. # function for any view, without having to repeat 'csrf_protect'.
  203. if not getattr(view, "csrf_exempt", False):
  204. inner = csrf_protect(inner)
  205. return update_wrapper(inner, view)
  206. def get_urls(self):
  207. # Since this module gets imported in the application's root package,
  208. # it cannot import models from other applications at the module level,
  209. # and django.contrib.contenttypes.views imports ContentType.
  210. from django.contrib.contenttypes import views as contenttype_views
  211. from django.urls import include, path, re_path
  212. def wrap(view, cacheable=False):
  213. def wrapper(*args, **kwargs):
  214. return self.admin_view(view, cacheable)(*args, **kwargs)
  215. wrapper.admin_site = self
  216. return update_wrapper(wrapper, view)
  217. # Admin-site-wide views.
  218. urlpatterns = [
  219. path("", wrap(self.index), name="index"),
  220. path("login/", self.login, name="login"),
  221. path("logout/", wrap(self.logout), name="logout"),
  222. path(
  223. "password_change/",
  224. wrap(self.password_change, cacheable=True),
  225. name="password_change",
  226. ),
  227. path(
  228. "password_change/done/",
  229. wrap(self.password_change_done, cacheable=True),
  230. name="password_change_done",
  231. ),
  232. path("autocomplete/", wrap(self.autocomplete_view), name="autocomplete"),
  233. path("jsi18n/", wrap(self.i18n_javascript, cacheable=True), name="jsi18n"),
  234. path(
  235. "r/<int:content_type_id>/<path:object_id>/",
  236. wrap(contenttype_views.shortcut),
  237. name="view_on_site",
  238. ),
  239. ]
  240. # Add in each model's views, and create a list of valid URLS for the
  241. # app_index
  242. valid_app_labels = []
  243. for model, model_admin in self._registry.items():
  244. urlpatterns += [
  245. path(
  246. "%s/%s/" % (model._meta.app_label, model._meta.model_name),
  247. include(model_admin.urls),
  248. ),
  249. ]
  250. if model._meta.app_label not in valid_app_labels:
  251. valid_app_labels.append(model._meta.app_label)
  252. # If there were ModelAdmins registered, we should have a list of app
  253. # labels for which we need to allow access to the app_index view,
  254. if valid_app_labels:
  255. regex = r"^(?P<app_label>" + "|".join(valid_app_labels) + ")/$"
  256. urlpatterns += [
  257. re_path(regex, wrap(self.app_index), name="app_list"),
  258. ]
  259. if self.final_catch_all_view:
  260. urlpatterns.append(re_path(r"(?P<url>.*)$", wrap(self.catch_all_view)))
  261. return urlpatterns
  262. @property
  263. def urls(self):
  264. return self.get_urls(), "admin", self.name
  265. def each_context(self, request):
  266. """
  267. Return a dictionary of variables to put in the template context for
  268. *every* page in the admin site.
  269. For sites running on a subpath, use the SCRIPT_NAME value if site_url
  270. hasn't been customized.
  271. """
  272. script_name = request.META["SCRIPT_NAME"]
  273. site_url = (
  274. script_name if self.site_url == "/" and script_name else self.site_url
  275. )
  276. return {
  277. "site_title": self.site_title,
  278. "site_header": self.site_header,
  279. "site_url": site_url,
  280. "has_permission": self.has_permission(request),
  281. "available_apps": self.get_app_list(request),
  282. "is_popup": False,
  283. "is_nav_sidebar_enabled": self.enable_nav_sidebar,
  284. }
  285. def password_change(self, request, extra_context=None):
  286. """
  287. Handle the "change password" task -- both form display and validation.
  288. """
  289. from django.contrib.admin.forms import AdminPasswordChangeForm
  290. from django.contrib.auth.views import PasswordChangeView
  291. url = reverse("admin:password_change_done", current_app=self.name)
  292. defaults = {
  293. "form_class": AdminPasswordChangeForm,
  294. "success_url": url,
  295. "extra_context": {**self.each_context(request), **(extra_context or {})},
  296. }
  297. if self.password_change_template is not None:
  298. defaults["template_name"] = self.password_change_template
  299. request.current_app = self.name
  300. return PasswordChangeView.as_view(**defaults)(request)
  301. def password_change_done(self, request, extra_context=None):
  302. """
  303. Display the "success" page after a password change.
  304. """
  305. from django.contrib.auth.views import PasswordChangeDoneView
  306. defaults = {
  307. "extra_context": {**self.each_context(request), **(extra_context or {})},
  308. }
  309. if self.password_change_done_template is not None:
  310. defaults["template_name"] = self.password_change_done_template
  311. request.current_app = self.name
  312. return PasswordChangeDoneView.as_view(**defaults)(request)
  313. def i18n_javascript(self, request, extra_context=None):
  314. """
  315. Display the i18n JavaScript that the Django admin requires.
  316. `extra_context` is unused but present for consistency with the other
  317. admin views.
  318. """
  319. return JavaScriptCatalog.as_view(packages=["django.contrib.admin"])(request)
  320. def logout(self, request, extra_context=None):
  321. """
  322. Log out the user for the given HttpRequest.
  323. This should *not* assume the user is already logged in.
  324. """
  325. from django.contrib.auth.views import LogoutView
  326. defaults = {
  327. "extra_context": {
  328. **self.each_context(request),
  329. # Since the user isn't logged out at this point, the value of
  330. # has_permission must be overridden.
  331. "has_permission": False,
  332. **(extra_context or {}),
  333. },
  334. }
  335. if self.logout_template is not None:
  336. defaults["template_name"] = self.logout_template
  337. request.current_app = self.name
  338. return LogoutView.as_view(**defaults)(request)
  339. @method_decorator(never_cache)
  340. def login(self, request, extra_context=None):
  341. """
  342. Display the login form for the given HttpRequest.
  343. """
  344. if request.method == "GET" and self.has_permission(request):
  345. # Already logged-in, redirect to admin index
  346. index_path = reverse("admin:index", current_app=self.name)
  347. return HttpResponseRedirect(index_path)
  348. # Since this module gets imported in the application's root package,
  349. # it cannot import models from other applications at the module level,
  350. # and django.contrib.admin.forms eventually imports User.
  351. from django.contrib.admin.forms import AdminAuthenticationForm
  352. from django.contrib.auth.views import LoginView
  353. context = {
  354. **self.each_context(request),
  355. "title": _("Log in"),
  356. "subtitle": None,
  357. "app_path": request.get_full_path(),
  358. "username": request.user.get_username(),
  359. }
  360. if (
  361. REDIRECT_FIELD_NAME not in request.GET
  362. and REDIRECT_FIELD_NAME not in request.POST
  363. ):
  364. context[REDIRECT_FIELD_NAME] = reverse("admin:index", current_app=self.name)
  365. context.update(extra_context or {})
  366. defaults = {
  367. "extra_context": context,
  368. "authentication_form": self.login_form or AdminAuthenticationForm,
  369. "template_name": self.login_template or "admin/login.html",
  370. }
  371. request.current_app = self.name
  372. return LoginView.as_view(**defaults)(request)
  373. def autocomplete_view(self, request):
  374. return AutocompleteJsonView.as_view(admin_site=self)(request)
  375. @no_append_slash
  376. def catch_all_view(self, request, url):
  377. if settings.APPEND_SLASH and not url.endswith("/"):
  378. urlconf = getattr(request, "urlconf", None)
  379. try:
  380. match = resolve("%s/" % request.path_info, urlconf)
  381. except Resolver404:
  382. pass
  383. else:
  384. if getattr(match.func, "should_append_slash", True):
  385. return HttpResponsePermanentRedirect("%s/" % request.path)
  386. raise Http404
  387. def _build_app_dict(self, request, label=None):
  388. """
  389. Build the app dictionary. The optional `label` parameter filters models
  390. of a specific app.
  391. """
  392. app_dict = {}
  393. if label:
  394. models = {
  395. m: m_a
  396. for m, m_a in self._registry.items()
  397. if m._meta.app_label == label
  398. }
  399. else:
  400. models = self._registry
  401. for model, model_admin in models.items():
  402. app_label = model._meta.app_label
  403. has_module_perms = model_admin.has_module_permission(request)
  404. if not has_module_perms:
  405. continue
  406. perms = model_admin.get_model_perms(request)
  407. # Check whether user has any perm for this module.
  408. # If so, add the module to the model_list.
  409. if True not in perms.values():
  410. continue
  411. info = (app_label, model._meta.model_name)
  412. model_dict = {
  413. "model": model,
  414. "name": capfirst(model._meta.verbose_name_plural),
  415. "object_name": model._meta.object_name,
  416. "perms": perms,
  417. "admin_url": None,
  418. "add_url": None,
  419. }
  420. if perms.get("change") or perms.get("view"):
  421. model_dict["view_only"] = not perms.get("change")
  422. try:
  423. model_dict["admin_url"] = reverse(
  424. "admin:%s_%s_changelist" % info, current_app=self.name
  425. )
  426. except NoReverseMatch:
  427. pass
  428. if perms.get("add"):
  429. try:
  430. model_dict["add_url"] = reverse(
  431. "admin:%s_%s_add" % info, current_app=self.name
  432. )
  433. except NoReverseMatch:
  434. pass
  435. if app_label in app_dict:
  436. app_dict[app_label]["models"].append(model_dict)
  437. else:
  438. app_dict[app_label] = {
  439. "name": apps.get_app_config(app_label).verbose_name,
  440. "app_label": app_label,
  441. "app_url": reverse(
  442. "admin:app_list",
  443. kwargs={"app_label": app_label},
  444. current_app=self.name,
  445. ),
  446. "has_module_perms": has_module_perms,
  447. "models": [model_dict],
  448. }
  449. return app_dict
  450. def get_app_list(self, request, app_label=None):
  451. """
  452. Return a sorted list of all the installed apps that have been
  453. registered in this site.
  454. """
  455. app_dict = self._build_app_dict(request, app_label)
  456. # Sort the apps alphabetically.
  457. app_list = sorted(app_dict.values(), key=lambda x: x["name"].lower())
  458. # Sort the models alphabetically within each app.
  459. for app in app_list:
  460. app["models"].sort(key=lambda x: x["name"])
  461. return app_list
  462. def index(self, request, extra_context=None):
  463. """
  464. Display the main admin index page, which lists all of the installed
  465. apps that have been registered in this site.
  466. """
  467. app_list = self.get_app_list(request)
  468. context = {
  469. **self.each_context(request),
  470. "title": self.index_title,
  471. "subtitle": None,
  472. "app_list": app_list,
  473. **(extra_context or {}),
  474. }
  475. request.current_app = self.name
  476. return TemplateResponse(
  477. request, self.index_template or "admin/index.html", context
  478. )
  479. def app_index(self, request, app_label, extra_context=None):
  480. app_list = self.get_app_list(request, app_label)
  481. if not app_list:
  482. raise Http404("The requested admin page does not exist.")
  483. context = {
  484. **self.each_context(request),
  485. "title": _("%(app)s administration") % {"app": app_list[0]["name"]},
  486. "subtitle": None,
  487. "app_list": app_list,
  488. "app_label": app_label,
  489. **(extra_context or {}),
  490. }
  491. request.current_app = self.name
  492. return TemplateResponse(
  493. request,
  494. self.app_index_template
  495. or ["admin/%s/app_index.html" % app_label, "admin/app_index.html"],
  496. context,
  497. )
  498. class DefaultAdminSite(LazyObject):
  499. def _setup(self):
  500. AdminSiteClass = import_string(apps.get_app_config("admin").default_site)
  501. self._wrapped = AdminSiteClass()
  502. def __repr__(self):
  503. return repr(self._wrapped)
  504. # This global object represents the default admin site, for the common case.
  505. # You can provide your own AdminSite using the (Simple)AdminConfig.default_site
  506. # attribute. You can also instantiate AdminSite in your own code to create a
  507. # custom admin site.
  508. site = DefaultAdminSite()