sites.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. import re
  2. from django import http, template
  3. from django.contrib.admin import ModelAdmin
  4. from django.contrib.auth import authenticate, login
  5. from django.db.models.base import ModelBase
  6. from django.core.exceptions import ImproperlyConfigured
  7. from django.shortcuts import render_to_response
  8. from django.utils.functional import update_wrapper
  9. from django.utils.safestring import mark_safe
  10. from django.utils.text import capfirst
  11. from django.utils.translation import ugettext_lazy, ugettext as _
  12. from django.views.decorators.cache import never_cache
  13. from django.conf import settings
  14. ERROR_MESSAGE = ugettext_lazy("Please enter a correct username and password. Note that both fields are case-sensitive.")
  15. LOGIN_FORM_KEY = 'this_is_the_login_form'
  16. class AlreadyRegistered(Exception):
  17. pass
  18. class NotRegistered(Exception):
  19. pass
  20. class AdminSite(object):
  21. """
  22. An AdminSite object encapsulates an instance of the Django admin application, ready
  23. to be hooked in to your URLConf. Models are registered with the AdminSite using the
  24. register() method, and the root() method can then be used as a Django view function
  25. that presents a full admin interface for the collection of registered models.
  26. """
  27. index_template = None
  28. login_template = None
  29. app_index_template = None
  30. def __init__(self, name=None):
  31. self._registry = {} # model_class class -> admin_class instance
  32. # TODO Root path is used to calculate urls under the old root() method
  33. # in order to maintain backwards compatibility we are leaving that in
  34. # so root_path isn't needed, not sure what to do about this.
  35. self.root_path = 'admin/'
  36. if name is None:
  37. name = ''
  38. else:
  39. name += '_'
  40. self.name = name
  41. self.actions = []
  42. def register(self, model_or_iterable, admin_class=None, **options):
  43. """
  44. Registers the given model(s) with the given admin class.
  45. The model(s) should be Model classes, not instances.
  46. If an admin class isn't given, it will use ModelAdmin (the default
  47. admin options). If keyword arguments are given -- e.g., list_display --
  48. they'll be applied as options to the admin class.
  49. If a model is already registered, this will raise AlreadyRegistered.
  50. """
  51. if not admin_class:
  52. admin_class = ModelAdmin
  53. # Don't import the humongous validation code unless required
  54. if admin_class and settings.DEBUG:
  55. from django.contrib.admin.validation import validate
  56. else:
  57. validate = lambda model, adminclass: None
  58. if isinstance(model_or_iterable, ModelBase):
  59. model_or_iterable = [model_or_iterable]
  60. for model in model_or_iterable:
  61. if model in self._registry:
  62. raise AlreadyRegistered('The model %s is already registered' % model.__name__)
  63. # If we got **options then dynamically construct a subclass of
  64. # admin_class with those **options.
  65. if options:
  66. # For reasons I don't quite understand, without a __module__
  67. # the created class appears to "live" in the wrong place,
  68. # which causes issues later on.
  69. options['__module__'] = __name__
  70. admin_class = type("%sAdmin" % model.__name__, (admin_class,), options)
  71. # Validate (which might be a no-op)
  72. validate(admin_class, model)
  73. # Instantiate the admin class to save in the registry
  74. self._registry[model] = admin_class(model, self)
  75. def unregister(self, model_or_iterable):
  76. """
  77. Unregisters the given model(s).
  78. If a model isn't already registered, this will raise NotRegistered.
  79. """
  80. if isinstance(model_or_iterable, ModelBase):
  81. model_or_iterable = [model_or_iterable]
  82. for model in model_or_iterable:
  83. if model not in self._registry:
  84. raise NotRegistered('The model %s is not registered' % model.__name__)
  85. del self._registry[model]
  86. def add_action(self, action):
  87. if not callable(action):
  88. raise TypeError("You can only register callable actions through an admin site")
  89. self.actions.append(action)
  90. def has_permission(self, request):
  91. """
  92. Returns True if the given HttpRequest has permission to view
  93. *at least one* page in the admin site.
  94. """
  95. return request.user.is_authenticated() and request.user.is_staff
  96. def check_dependencies(self):
  97. """
  98. Check that all things needed to run the admin have been correctly installed.
  99. The default implementation checks that LogEntry, ContentType and the
  100. auth context processor are installed.
  101. """
  102. from django.contrib.admin.models import LogEntry
  103. from django.contrib.contenttypes.models import ContentType
  104. if not LogEntry._meta.installed:
  105. raise ImproperlyConfigured("Put 'django.contrib.admin' in your INSTALLED_APPS setting in order to use the admin application.")
  106. if not ContentType._meta.installed:
  107. raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in your INSTALLED_APPS setting in order to use the admin application.")
  108. if 'django.core.context_processors.auth' not in settings.TEMPLATE_CONTEXT_PROCESSORS:
  109. raise ImproperlyConfigured("Put 'django.core.context_processors.auth' in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.")
  110. def admin_view(self, view):
  111. """
  112. Decorator to create an "admin view attached to this ``AdminSite``. This
  113. wraps the view and provides permission checking by calling
  114. ``self.has_permission``.
  115. You'll want to use this from within ``AdminSite.get_urls()``:
  116. class MyAdminSite(AdminSite):
  117. def get_urls(self):
  118. from django.conf.urls.defaults import patterns, url
  119. urls = super(MyAdminSite, self).get_urls()
  120. urls += patterns('',
  121. url(r'^my_view/$', self.protected_view(some_view))
  122. )
  123. return urls
  124. """
  125. def inner(request, *args, **kwargs):
  126. if not self.has_permission(request):
  127. return self.login(request)
  128. return view(request, *args, **kwargs)
  129. return update_wrapper(inner, view)
  130. def get_urls(self):
  131. from django.conf.urls.defaults import patterns, url, include
  132. def wrap(view):
  133. def wrapper(*args, **kwargs):
  134. return self.admin_view(view)(*args, **kwargs)
  135. return update_wrapper(wrapper, view)
  136. # Admin-site-wide views.
  137. urlpatterns = patterns('',
  138. url(r'^$',
  139. wrap(self.index),
  140. name='%sadmin_index' % self.name),
  141. url(r'^logout/$',
  142. wrap(self.logout),
  143. name='%sadmin_logout'),
  144. url(r'^password_change/$',
  145. wrap(self.password_change),
  146. name='%sadmin_password_change' % self.name),
  147. url(r'^password_change/done/$',
  148. wrap(self.password_change_done),
  149. name='%sadmin_password_change_done' % self.name),
  150. url(r'^jsi18n/$',
  151. wrap(self.i18n_javascript),
  152. name='%sadmin_jsi18n' % self.name),
  153. url(r'^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$',
  154. 'django.views.defaults.shortcut'),
  155. url(r'^(?P<app_label>\w+)/$',
  156. wrap(self.app_index),
  157. name='%sadmin_app_list' % self.name),
  158. )
  159. # Add in each model's views.
  160. for model, model_admin in self._registry.iteritems():
  161. urlpatterns += patterns('',
  162. url(r'^%s/%s/' % (model._meta.app_label, model._meta.module_name),
  163. include(model_admin.urls))
  164. )
  165. return urlpatterns
  166. def urls(self):
  167. return self.get_urls()
  168. urls = property(urls)
  169. def password_change(self, request):
  170. """
  171. Handles the "change password" task -- both form display and validation.
  172. """
  173. from django.contrib.auth.views import password_change
  174. return password_change(request,
  175. post_change_redirect='%spassword_change/done/' % self.root_path)
  176. def password_change_done(self, request):
  177. """
  178. Displays the "success" page after a password change.
  179. """
  180. from django.contrib.auth.views import password_change_done
  181. return password_change_done(request)
  182. def i18n_javascript(self, request):
  183. """
  184. Displays the i18n JavaScript that the Django admin requires.
  185. This takes into account the USE_I18N setting. If it's set to False, the
  186. generated JavaScript will be leaner and faster.
  187. """
  188. if settings.USE_I18N:
  189. from django.views.i18n import javascript_catalog
  190. else:
  191. from django.views.i18n import null_javascript_catalog as javascript_catalog
  192. return javascript_catalog(request, packages='django.conf')
  193. def logout(self, request):
  194. """
  195. Logs out the user for the given HttpRequest.
  196. This should *not* assume the user is already logged in.
  197. """
  198. from django.contrib.auth.views import logout
  199. return logout(request)
  200. logout = never_cache(logout)
  201. def login(self, request):
  202. """
  203. Displays the login form for the given HttpRequest.
  204. """
  205. from django.contrib.auth.models import User
  206. # If this isn't already the login page, display it.
  207. if not request.POST.has_key(LOGIN_FORM_KEY):
  208. if request.POST:
  209. message = _("Please log in again, because your session has expired.")
  210. else:
  211. message = ""
  212. return self.display_login_form(request, message)
  213. # Check that the user accepts cookies.
  214. if not request.session.test_cookie_worked():
  215. message = _("Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again.")
  216. return self.display_login_form(request, message)
  217. else:
  218. request.session.delete_test_cookie()
  219. # Check the password.
  220. username = request.POST.get('username', None)
  221. password = request.POST.get('password', None)
  222. user = authenticate(username=username, password=password)
  223. if user is None:
  224. message = ERROR_MESSAGE
  225. if u'@' in username:
  226. # Mistakenly entered e-mail address instead of username? Look it up.
  227. try:
  228. user = User.objects.get(email=username)
  229. except (User.DoesNotExist, User.MultipleObjectsReturned):
  230. message = _("Usernames cannot contain the '@' character.")
  231. else:
  232. if user.check_password(password):
  233. message = _("Your e-mail address is not your username."
  234. " Try '%s' instead.") % user.username
  235. else:
  236. message = _("Usernames cannot contain the '@' character.")
  237. return self.display_login_form(request, message)
  238. # The user data is correct; log in the user in and continue.
  239. else:
  240. if user.is_active and user.is_staff:
  241. login(request, user)
  242. return http.HttpResponseRedirect(request.get_full_path())
  243. else:
  244. return self.display_login_form(request, ERROR_MESSAGE)
  245. login = never_cache(login)
  246. def index(self, request, extra_context=None):
  247. """
  248. Displays the main admin index page, which lists all of the installed
  249. apps that have been registered in this site.
  250. """
  251. app_dict = {}
  252. user = request.user
  253. for model, model_admin in self._registry.items():
  254. app_label = model._meta.app_label
  255. has_module_perms = user.has_module_perms(app_label)
  256. if has_module_perms:
  257. perms = {
  258. 'add': model_admin.has_add_permission(request),
  259. 'change': model_admin.has_change_permission(request),
  260. 'delete': model_admin.has_delete_permission(request),
  261. }
  262. # Check whether user has any perm for this module.
  263. # If so, add the module to the model_list.
  264. if True in perms.values():
  265. model_dict = {
  266. 'name': capfirst(model._meta.verbose_name_plural),
  267. 'admin_url': mark_safe('%s/%s/' % (app_label, model.__name__.lower())),
  268. 'perms': perms,
  269. }
  270. if app_label in app_dict:
  271. app_dict[app_label]['models'].append(model_dict)
  272. else:
  273. app_dict[app_label] = {
  274. 'name': app_label.title(),
  275. 'app_url': app_label + '/',
  276. 'has_module_perms': has_module_perms,
  277. 'models': [model_dict],
  278. }
  279. # Sort the apps alphabetically.
  280. app_list = app_dict.values()
  281. app_list.sort(lambda x, y: cmp(x['name'], y['name']))
  282. # Sort the models alphabetically within each app.
  283. for app in app_list:
  284. app['models'].sort(lambda x, y: cmp(x['name'], y['name']))
  285. context = {
  286. 'title': _('Site administration'),
  287. 'app_list': app_list,
  288. 'root_path': self.root_path,
  289. }
  290. context.update(extra_context or {})
  291. return render_to_response(self.index_template or 'admin/index.html', context,
  292. context_instance=template.RequestContext(request)
  293. )
  294. index = never_cache(index)
  295. def display_login_form(self, request, error_message='', extra_context=None):
  296. request.session.set_test_cookie()
  297. context = {
  298. 'title': _('Log in'),
  299. 'app_path': request.get_full_path(),
  300. 'error_message': error_message,
  301. 'root_path': self.root_path,
  302. }
  303. context.update(extra_context or {})
  304. return render_to_response(self.login_template or 'admin/login.html', context,
  305. context_instance=template.RequestContext(request)
  306. )
  307. def app_index(self, request, app_label, extra_context=None):
  308. user = request.user
  309. has_module_perms = user.has_module_perms(app_label)
  310. app_dict = {}
  311. for model, model_admin in self._registry.items():
  312. if app_label == model._meta.app_label:
  313. if has_module_perms:
  314. perms = {
  315. 'add': user.has_perm("%s.%s" % (app_label, model._meta.get_add_permission())),
  316. 'change': user.has_perm("%s.%s" % (app_label, model._meta.get_change_permission())),
  317. 'delete': user.has_perm("%s.%s" % (app_label, model._meta.get_delete_permission())),
  318. }
  319. # Check whether user has any perm for this module.
  320. # If so, add the module to the model_list.
  321. if True in perms.values():
  322. model_dict = {
  323. 'name': capfirst(model._meta.verbose_name_plural),
  324. 'admin_url': '%s/' % model.__name__.lower(),
  325. 'perms': perms,
  326. }
  327. if app_dict:
  328. app_dict['models'].append(model_dict),
  329. else:
  330. # First time around, now that we know there's
  331. # something to display, add in the necessary meta
  332. # information.
  333. app_dict = {
  334. 'name': app_label.title(),
  335. 'app_url': '',
  336. 'has_module_perms': has_module_perms,
  337. 'models': [model_dict],
  338. }
  339. if not app_dict:
  340. raise http.Http404('The requested admin page does not exist.')
  341. # Sort the models alphabetically within each app.
  342. app_dict['models'].sort(lambda x, y: cmp(x['name'], y['name']))
  343. context = {
  344. 'title': _('%s administration') % capfirst(app_label),
  345. 'app_list': [app_dict],
  346. 'root_path': self.root_path,
  347. }
  348. context.update(extra_context or {})
  349. return render_to_response(self.app_index_template or 'admin/app_index.html', context,
  350. context_instance=template.RequestContext(request)
  351. )
  352. def root(self, request, url):
  353. """
  354. DEPRECATED. This function is the old way of handling URL resolution, and
  355. is deprecated in favor of real URL resolution -- see ``get_urls()``.
  356. This function still exists for backwards-compatibility; it will be
  357. removed in Django 1.3.
  358. """
  359. import warnings
  360. warnings.warn(
  361. "AdminSite.root() is deprecated; use include(admin.site.urls) instead.",
  362. PendingDeprecationWarning
  363. )
  364. #
  365. # Again, remember that the following only exists for
  366. # backwards-compatibility. Any new URLs, changes to existing URLs, or
  367. # whatever need to be done up in get_urls(), above!
  368. #
  369. if request.method == 'GET' and not request.path.endswith('/'):
  370. return http.HttpResponseRedirect(request.path + '/')
  371. if settings.DEBUG:
  372. self.check_dependencies()
  373. # Figure out the admin base URL path and stash it for later use
  374. self.root_path = re.sub(re.escape(url) + '$', '', request.path)
  375. url = url.rstrip('/') # Trim trailing slash, if it exists.
  376. # The 'logout' view doesn't require that the person is logged in.
  377. if url == 'logout':
  378. return self.logout(request)
  379. # Check permission to continue or display login form.
  380. if not self.has_permission(request):
  381. return self.login(request)
  382. if url == '':
  383. return self.index(request)
  384. elif url == 'password_change':
  385. return self.password_change(request)
  386. elif url == 'password_change/done':
  387. return self.password_change_done(request)
  388. elif url == 'jsi18n':
  389. return self.i18n_javascript(request)
  390. # URLs starting with 'r/' are for the "View on site" links.
  391. elif url.startswith('r/'):
  392. from django.contrib.contenttypes.views import shortcut
  393. return shortcut(request, *url.split('/')[1:])
  394. else:
  395. if '/' in url:
  396. return self.model_page(request, *url.split('/', 2))
  397. else:
  398. return self.app_index(request, url)
  399. raise http.Http404('The requested admin page does not exist.')
  400. def model_page(self, request, app_label, model_name, rest_of_url=None):
  401. """
  402. DEPRECATED. This is the old way of handling a model view on the admin
  403. site; the new views should use get_urls(), above.
  404. """
  405. from django.db import models
  406. model = models.get_model(app_label, model_name)
  407. if model is None:
  408. raise http.Http404("App %r, model %r, not found." % (app_label, model_name))
  409. try:
  410. admin_obj = self._registry[model]
  411. except KeyError:
  412. raise http.Http404("This model exists but has not been registered with the admin site.")
  413. return admin_obj(request, rest_of_url)
  414. model_page = never_cache(model_page)
  415. # This global object represents the default admin site, for the common case.
  416. # You can instantiate AdminSite in your own code to create a custom admin site.
  417. site = AdminSite()