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.
 
 
 
 

543 lines
21 KiB

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