sites.py 22 KB

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