sites.py 21 KB

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