sites.py 23 KB

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