PageRenderTime 62ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/django/contrib/admin/sites.py

https://code.google.com/p/mango-py/
Python | 432 lines | 371 code | 13 blank | 48 comment | 13 complexity | 511091bddd26f1ae2d7cf39b4df6cd97 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. import re
  2. from django import http, template
  3. from django.contrib.admin import ModelAdmin, actions
  4. from django.contrib.admin.forms import AdminAuthenticationForm
  5. from django.contrib.auth import REDIRECT_FIELD_NAME
  6. from django.contrib.contenttypes import views as contenttype_views
  7. from django.views.decorators.csrf import csrf_protect
  8. from django.db.models.base import ModelBase
  9. from django.core.exceptions import ImproperlyConfigured
  10. from django.core.urlresolvers import reverse
  11. from django.shortcuts import render_to_response
  12. from django.utils.functional import update_wrapper
  13. from django.utils.safestring import mark_safe
  14. from django.utils.text import capfirst
  15. from django.utils.translation import ugettext as _
  16. from django.views.decorators.cache import never_cache
  17. from django.conf import settings
  18. LOGIN_FORM_KEY = 'this_is_the_login_form'
  19. class AlreadyRegistered(Exception):
  20. pass
  21. class NotRegistered(Exception):
  22. pass
  23. class AdminSite(object):
  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. login_form = None
  32. index_template = None
  33. app_index_template = None
  34. login_template = None
  35. logout_template = None
  36. password_change_template = None
  37. password_change_done_template = None
  38. def __init__(self, name=None, app_name='admin'):
  39. self._registry = {} # model_class class -> admin_class instance
  40. self.root_path = None
  41. if name is None:
  42. self.name = 'admin'
  43. else:
  44. self.name = name
  45. self.app_name = app_name
  46. self._actions = {'delete_selected': actions.delete_selected}
  47. self._global_actions = self._actions.copy()
  48. def register(self, model_or_iterable, admin_class=None, **options):
  49. """
  50. Registers the given model(s) with the given admin class.
  51. The model(s) should be Model classes, not instances.
  52. If an admin class isn't given, it will use ModelAdmin (the default
  53. admin options). If keyword arguments are given -- e.g., list_display --
  54. they'll be applied as options to the admin class.
  55. If a model is already registered, this will raise AlreadyRegistered.
  56. If a model is abstract, this will raise ImproperlyConfigured.
  57. """
  58. if not admin_class:
  59. admin_class = ModelAdmin
  60. # Don't import the humongous validation code unless required
  61. if admin_class and settings.DEBUG:
  62. from django.contrib.admin.validation import validate
  63. else:
  64. validate = lambda model, adminclass: None
  65. if isinstance(model_or_iterable, ModelBase):
  66. model_or_iterable = [model_or_iterable]
  67. for model in model_or_iterable:
  68. if model._meta.abstract:
  69. raise ImproperlyConfigured('The model %s is abstract, so it '
  70. 'cannot be registered with admin.' % model.__name__)
  71. if model in self._registry:
  72. raise AlreadyRegistered('The model %s is already registered' % model.__name__)
  73. # If we got **options then dynamically construct a subclass of
  74. # admin_class with those **options.
  75. if options:
  76. # For reasons I don't quite understand, without a __module__
  77. # the created class appears to "live" in the wrong place,
  78. # which causes issues later on.
  79. options['__module__'] = __name__
  80. admin_class = type("%sAdmin" % model.__name__, (admin_class,), options)
  81. # Validate (which might be a no-op)
  82. validate(admin_class, model)
  83. # Instantiate the admin class to save in the registry
  84. self._registry[model] = admin_class(model, self)
  85. def unregister(self, model_or_iterable):
  86. """
  87. Unregisters the given model(s).
  88. If a model isn't already registered, this will raise NotRegistered.
  89. """
  90. if isinstance(model_or_iterable, ModelBase):
  91. model_or_iterable = [model_or_iterable]
  92. for model in model_or_iterable:
  93. if model not in self._registry:
  94. raise NotRegistered('The model %s is not registered' % model.__name__)
  95. del self._registry[model]
  96. def add_action(self, action, name=None):
  97. """
  98. Register an action to be available globally.
  99. """
  100. name = name or action.__name__
  101. self._actions[name] = action
  102. self._global_actions[name] = action
  103. def disable_action(self, name):
  104. """
  105. Disable a globally-registered action. Raises KeyError for invalid names.
  106. """
  107. del self._actions[name]
  108. def get_action(self, name):
  109. """
  110. Explicitally get a registered global action wheather it's enabled or
  111. not. Raises KeyError for invalid names.
  112. """
  113. return self._global_actions[name]
  114. @property
  115. def actions(self):
  116. """
  117. Get all the enabled actions as an iterable of (name, func).
  118. """
  119. return self._actions.iteritems()
  120. def has_permission(self, request):
  121. """
  122. Returns True if the given HttpRequest has permission to view
  123. *at least one* page in the admin site.
  124. """
  125. return request.user.is_active and request.user.is_staff
  126. def check_dependencies(self):
  127. """
  128. Check that all things needed to run the admin have been correctly installed.
  129. The default implementation checks that LogEntry, ContentType and the
  130. auth context processor are installed.
  131. """
  132. from django.contrib.admin.models import LogEntry
  133. from django.contrib.contenttypes.models import ContentType
  134. if not LogEntry._meta.installed:
  135. raise ImproperlyConfigured("Put 'django.contrib.admin' in your "
  136. "INSTALLED_APPS setting in order to use the admin application.")
  137. if not ContentType._meta.installed:
  138. raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in "
  139. "your INSTALLED_APPS setting in order to use the admin application.")
  140. if not ('django.contrib.auth.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS or
  141. 'django.core.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS):
  142. raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' "
  143. "in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.")
  144. def admin_view(self, view, cacheable=False):
  145. """
  146. Decorator to create an admin view attached to this ``AdminSite``. This
  147. wraps the view and provides permission checking by calling
  148. ``self.has_permission``.
  149. You'll want to use this from within ``AdminSite.get_urls()``:
  150. class MyAdminSite(AdminSite):
  151. def get_urls(self):
  152. from django.conf.urls.defaults import patterns, url
  153. urls = super(MyAdminSite, self).get_urls()
  154. urls += patterns('',
  155. url(r'^my_view/$', self.admin_view(some_view))
  156. )
  157. return urls
  158. By default, admin_views are marked non-cacheable using the
  159. ``never_cache`` decorator. If the view can be safely cached, set
  160. cacheable=True.
  161. """
  162. def inner(request, *args, **kwargs):
  163. if not self.has_permission(request):
  164. return self.login(request)
  165. return view(request, *args, **kwargs)
  166. if not cacheable:
  167. inner = never_cache(inner)
  168. # We add csrf_protect here so this function can be used as a utility
  169. # function for any view, without having to repeat 'csrf_protect'.
  170. if not getattr(view, 'csrf_exempt', False):
  171. inner = csrf_protect(inner)
  172. return update_wrapper(inner, view)
  173. def get_urls(self):
  174. from django.conf.urls.defaults import patterns, url, include
  175. if settings.DEBUG:
  176. self.check_dependencies()
  177. def wrap(view, cacheable=False):
  178. def wrapper(*args, **kwargs):
  179. return self.admin_view(view, cacheable)(*args, **kwargs)
  180. return update_wrapper(wrapper, view)
  181. # Admin-site-wide views.
  182. urlpatterns = patterns('',
  183. url(r'^$',
  184. wrap(self.index),
  185. name='index'),
  186. url(r'^logout/$',
  187. wrap(self.logout),
  188. name='logout'),
  189. url(r'^password_change/$',
  190. wrap(self.password_change, cacheable=True),
  191. name='password_change'),
  192. url(r'^password_change/done/$',
  193. wrap(self.password_change_done, cacheable=True),
  194. name='password_change_done'),
  195. url(r'^jsi18n/$',
  196. wrap(self.i18n_javascript, cacheable=True),
  197. name='jsi18n'),
  198. url(r'^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$',
  199. wrap(contenttype_views.shortcut)),
  200. url(r'^(?P<app_label>\w+)/$',
  201. wrap(self.app_index),
  202. name='app_list')
  203. )
  204. # Add in each model's views.
  205. for model, model_admin in self._registry.iteritems():
  206. urlpatterns += patterns('',
  207. url(r'^%s/%s/' % (model._meta.app_label, model._meta.module_name),
  208. include(model_admin.urls))
  209. )
  210. return urlpatterns
  211. @property
  212. def urls(self):
  213. return self.get_urls(), self.app_name, self.name
  214. def password_change(self, request):
  215. """
  216. Handles the "change password" task -- both form display and validation.
  217. """
  218. from django.contrib.auth.views import password_change
  219. if self.root_path is not None:
  220. url = '%spassword_change/done/' % self.root_path
  221. else:
  222. url = reverse('admin:password_change_done', current_app=self.name)
  223. defaults = {
  224. 'current_app': self.name,
  225. 'post_change_redirect': url
  226. }
  227. if self.password_change_template is not None:
  228. defaults['template_name'] = self.password_change_template
  229. return password_change(request, **defaults)
  230. def password_change_done(self, request, extra_context=None):
  231. """
  232. Displays the "success" page after a password change.
  233. """
  234. from django.contrib.auth.views import password_change_done
  235. defaults = {
  236. 'current_app': self.name,
  237. 'extra_context': extra_context or {},
  238. }
  239. if self.password_change_done_template is not None:
  240. defaults['template_name'] = self.password_change_done_template
  241. return password_change_done(request, **defaults)
  242. def i18n_javascript(self, request):
  243. """
  244. Displays the i18n JavaScript that the Django admin requires.
  245. This takes into account the USE_I18N setting. If it's set to False, the
  246. generated JavaScript will be leaner and faster.
  247. """
  248. if settings.USE_I18N:
  249. from django.views.i18n import javascript_catalog
  250. else:
  251. from django.views.i18n import null_javascript_catalog as javascript_catalog
  252. return javascript_catalog(request, packages=['django.conf', 'django.contrib.admin'])
  253. @never_cache
  254. def logout(self, request, extra_context=None):
  255. """
  256. Logs out the user for the given HttpRequest.
  257. This should *not* assume the user is already logged in.
  258. """
  259. from django.contrib.auth.views import logout
  260. defaults = {
  261. 'current_app': self.name,
  262. 'extra_context': extra_context or {},
  263. }
  264. if self.logout_template is not None:
  265. defaults['template_name'] = self.logout_template
  266. return logout(request, **defaults)
  267. @never_cache
  268. def login(self, request, extra_context=None):
  269. """
  270. Displays the login form for the given HttpRequest.
  271. """
  272. from django.contrib.auth.views import login
  273. context = {
  274. 'title': _('Log in'),
  275. 'root_path': self.root_path,
  276. 'app_path': request.get_full_path(),
  277. REDIRECT_FIELD_NAME: request.get_full_path(),
  278. }
  279. context.update(extra_context or {})
  280. defaults = {
  281. 'extra_context': context,
  282. 'current_app': self.name,
  283. 'authentication_form': self.login_form or AdminAuthenticationForm,
  284. 'template_name': self.login_template or 'admin/login.html',
  285. }
  286. return login(request, **defaults)
  287. @never_cache
  288. def index(self, request, extra_context=None):
  289. """
  290. Displays the main admin index page, which lists all of the installed
  291. apps that have been registered in this site.
  292. """
  293. app_dict = {}
  294. user = request.user
  295. for model, model_admin in self._registry.items():
  296. app_label = model._meta.app_label
  297. has_module_perms = user.has_module_perms(app_label)
  298. if has_module_perms:
  299. perms = model_admin.get_model_perms(request)
  300. # Check whether user has any perm for this module.
  301. # If so, add the module to the model_list.
  302. if True in perms.values():
  303. model_dict = {
  304. 'name': capfirst(model._meta.verbose_name_plural),
  305. 'admin_url': mark_safe('%s/%s/' % (app_label, model.__name__.lower())),
  306. 'perms': perms,
  307. }
  308. if app_label in app_dict:
  309. app_dict[app_label]['models'].append(model_dict)
  310. else:
  311. app_dict[app_label] = {
  312. 'name': app_label.title(),
  313. 'app_url': app_label + '/',
  314. 'has_module_perms': has_module_perms,
  315. 'models': [model_dict],
  316. }
  317. # Sort the apps alphabetically.
  318. app_list = app_dict.values()
  319. app_list.sort(key=lambda x: x['name'])
  320. # Sort the models alphabetically within each app.
  321. for app in app_list:
  322. app['models'].sort(key=lambda x: x['name'])
  323. context = {
  324. 'title': _('Site administration'),
  325. 'app_list': app_list,
  326. 'root_path': self.root_path,
  327. }
  328. context.update(extra_context or {})
  329. context_instance = template.RequestContext(request, current_app=self.name)
  330. return render_to_response(self.index_template or 'admin/index.html', context,
  331. context_instance=context_instance
  332. )
  333. def app_index(self, request, app_label, extra_context=None):
  334. user = request.user
  335. has_module_perms = user.has_module_perms(app_label)
  336. app_dict = {}
  337. for model, model_admin in self._registry.items():
  338. if app_label == model._meta.app_label:
  339. if has_module_perms:
  340. perms = model_admin.get_model_perms(request)
  341. # Check whether user has any perm for this module.
  342. # If so, add the module to the model_list.
  343. if True in perms.values():
  344. model_dict = {
  345. 'name': capfirst(model._meta.verbose_name_plural),
  346. 'admin_url': '%s/' % model.__name__.lower(),
  347. 'perms': perms,
  348. }
  349. if app_dict:
  350. app_dict['models'].append(model_dict),
  351. else:
  352. # First time around, now that we know there's
  353. # something to display, add in the necessary meta
  354. # information.
  355. app_dict = {
  356. 'name': app_label.title(),
  357. 'app_url': '',
  358. 'has_module_perms': has_module_perms,
  359. 'models': [model_dict],
  360. }
  361. if not app_dict:
  362. raise http.Http404('The requested admin page does not exist.')
  363. # Sort the models alphabetically within each app.
  364. app_dict['models'].sort(key=lambda x: x['name'])
  365. context = {
  366. 'title': _('%s administration') % capfirst(app_label),
  367. 'app_list': [app_dict],
  368. 'root_path': self.root_path,
  369. }
  370. context.update(extra_context or {})
  371. context_instance = template.RequestContext(request, current_app=self.name)
  372. return render_to_response(self.app_index_template or ('admin/%s/app_index.html' % app_label,
  373. 'admin/app_index.html'), context,
  374. context_instance=context_instance
  375. )
  376. # This global object represents the default admin site, for the common case.
  377. # You can instantiate AdminSite in your own code to create a custom admin site.
  378. site = AdminSite()