You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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