sites.py 20 KB

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