sites.py 22 KB

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