PageRenderTime 39ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/django/branches/attic/newforms-admin/django/contrib/admin/sites.py

https://bitbucket.org/mirror/django/
Python | 349 lines | 304 code | 16 blank | 29 comment | 16 complexity | 72519557dd356d9570f9c58c403e101e MD5 | raw file
Possible License(s): BSD-3-Clause
  1. from django import http, template
  2. from django.contrib.admin import ModelAdmin
  3. from django.contrib.auth import authenticate, login
  4. from django.db.models.base import ModelBase
  5. from django.shortcuts import render_to_response
  6. from django.utils.safestring import mark_safe
  7. from django.utils.text import capfirst
  8. from django.utils.translation import ugettext_lazy, ugettext as _
  9. from django.views.decorators.cache import never_cache
  10. from django.conf import settings
  11. import base64
  12. import cPickle as pickle
  13. import datetime
  14. import md5
  15. import re
  16. ERROR_MESSAGE = ugettext_lazy("Please enter a correct username and password. Note that both fields are case-sensitive.")
  17. LOGIN_FORM_KEY = 'this_is_the_login_form'
  18. USER_CHANGE_PASSWORD_URL_RE = re.compile('auth/user/(\d+)/password')
  19. class AlreadyRegistered(Exception):
  20. pass
  21. class NotRegistered(Exception):
  22. pass
  23. def _encode_post_data(post_data):
  24. from django.conf import settings
  25. pickled = pickle.dumps(post_data)
  26. pickled_md5 = md5.new(pickled + settings.SECRET_KEY).hexdigest()
  27. return base64.encodestring(pickled + pickled_md5)
  28. def _decode_post_data(encoded_data):
  29. from django.conf import settings
  30. encoded_data = base64.decodestring(encoded_data)
  31. pickled, tamper_check = encoded_data[:-32], encoded_data[-32:]
  32. if md5.new(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
  33. from django.core.exceptions import SuspiciousOperation
  34. raise SuspiciousOperation, "User may have tampered with session cookie."
  35. return pickle.loads(pickled)
  36. class AdminSite(object):
  37. """
  38. An AdminSite object encapsulates an instance of the Django admin application, ready
  39. to be hooked in to your URLConf. Models are registered with the AdminSite using the
  40. register() method, and the root() method can then be used as a Django view function
  41. that presents a full admin interface for the collection of registered models.
  42. """
  43. index_template = None
  44. login_template = None
  45. def __init__(self):
  46. self._registry = {} # model_class class -> admin_class instance
  47. def register(self, model_or_iterable, admin_class=None, **options):
  48. """
  49. Registers the given model(s) with the given admin class.
  50. The model(s) should be Model classes, not instances.
  51. If an admin class isn't given, it will use ModelAdmin (the default
  52. admin options). If keyword arguments are given -- e.g., list_display --
  53. they'll be applied as options to the admin class.
  54. If a model is already registered, this will raise AlreadyRegistered.
  55. """
  56. do_validate = admin_class and settings.DEBUG
  57. if do_validate:
  58. # don't import the humongous validation code unless required
  59. from django.contrib.admin.validation import validate
  60. admin_class = admin_class or ModelAdmin
  61. # TODO: Handle options
  62. if isinstance(model_or_iterable, ModelBase):
  63. model_or_iterable = [model_or_iterable]
  64. for model in model_or_iterable:
  65. if model in self._registry:
  66. raise AlreadyRegistered('The model %s is already registered' % model.__name__)
  67. if do_validate:
  68. validate(admin_class, model)
  69. self._registry[model] = admin_class(model, self)
  70. def unregister(self, model_or_iterable):
  71. """
  72. Unregisters the given model(s).
  73. If a model isn't already registered, this will raise NotRegistered.
  74. """
  75. if isinstance(model_or_iterable, ModelBase):
  76. model_or_iterable = [model_or_iterable]
  77. for model in model_or_iterable:
  78. if model not in self._registry:
  79. raise NotRegistered('The model %s is not registered' % model.__name__)
  80. del self._registry[model]
  81. def has_permission(self, request):
  82. """
  83. Returns True if the given HttpRequest has permission to view
  84. *at least one* page in the admin site.
  85. """
  86. return request.user.is_authenticated() and request.user.is_staff
  87. def root(self, request, url):
  88. """
  89. Handles main URL routing for the admin app.
  90. `url` is the remainder of the URL -- e.g. 'comments/comment/'.
  91. """
  92. if request.method == 'GET' and not request.path.endswith('/'):
  93. return http.HttpResponseRedirect(request.path + '/')
  94. # Figure out the admin base URL path and stash it for later use
  95. self.root_path = re.sub(re.escape(url) + '$', '', request.path)
  96. url = url.rstrip('/') # Trim trailing slash, if it exists.
  97. # The 'logout' view doesn't require that the person is logged in.
  98. if url == 'logout':
  99. return self.logout(request)
  100. # Check permission to continue or display login form.
  101. if not self.has_permission(request):
  102. return self.login(request)
  103. if url == '':
  104. return self.index(request)
  105. elif url == 'password_change':
  106. return self.password_change(request)
  107. elif url == 'password_change/done':
  108. return self.password_change_done(request)
  109. elif url == 'jsi18n':
  110. return self.i18n_javascript(request)
  111. # urls starting with 'r/' are for the "show in web" links
  112. elif url.startswith('r/'):
  113. from django.views.defaults import shortcut
  114. return shortcut(request, *url.split('/')[1:])
  115. else:
  116. match = USER_CHANGE_PASSWORD_URL_RE.match(url)
  117. if match:
  118. return self.user_change_password(request, match.group(1))
  119. if '/' in url:
  120. return self.model_page(request, *url.split('/', 2))
  121. raise http.Http404('The requested admin page does not exist.')
  122. def model_page(self, request, app_label, model_name, rest_of_url=None):
  123. """
  124. Handles the model-specific functionality of the admin site, delegating
  125. to the appropriate ModelAdmin class.
  126. """
  127. from django.db import models
  128. model = models.get_model(app_label, model_name)
  129. if model is None:
  130. raise http.Http404("App %r, model %r, not found." % (app_label, model_name))
  131. try:
  132. admin_obj = self._registry[model]
  133. except KeyError:
  134. raise http.Http404("This model exists but has not been registered with the admin site.")
  135. return admin_obj(request, rest_of_url)
  136. model_page = never_cache(model_page)
  137. def password_change(self, request):
  138. """
  139. Handles the "change password" task -- both form display and validation.
  140. """
  141. from django.contrib.auth.views import password_change
  142. return password_change(request)
  143. def password_change_done(self, request):
  144. """
  145. Displays the "success" page after a password change.
  146. """
  147. from django.contrib.auth.views import password_change_done
  148. return password_change_done(request)
  149. def user_change_password(self, request, id):
  150. """
  151. Handles the "user change password" task
  152. """
  153. from django.contrib.auth.views import user_change_password
  154. return user_change_password(request, id)
  155. def i18n_javascript(self, request):
  156. """
  157. Displays the i18n JavaScript that the Django admin requires.
  158. This takes into account the USE_I18N setting. If it's set to False, the
  159. generated JavaScript will be leaner and faster.
  160. """
  161. from django.conf import settings
  162. if settings.USE_I18N:
  163. from django.views.i18n import javascript_catalog
  164. else:
  165. from django.views.i18n import null_javascript_catalog as javascript_catalog
  166. return javascript_catalog(request, packages='django.conf')
  167. def logout(self, request):
  168. """
  169. Logs out the user for the given HttpRequest.
  170. This should *not* assume the user is already logged in.
  171. """
  172. from django.contrib.auth.views import logout
  173. return logout(request)
  174. logout = never_cache(logout)
  175. def login(self, request):
  176. """
  177. Displays the login form for the given HttpRequest.
  178. """
  179. from django.contrib.auth.models import User
  180. # If this isn't already the login page, display it.
  181. if not request.POST.has_key(LOGIN_FORM_KEY):
  182. if request.POST:
  183. message = _("Please log in again, because your session has expired. Don't worry: Your submission has been saved.")
  184. else:
  185. message = ""
  186. return self.display_login_form(request, message)
  187. # Check that the user accepts cookies.
  188. if not request.session.test_cookie_worked():
  189. message = _("Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again.")
  190. return self.display_login_form(request, message)
  191. # Check the password.
  192. username = request.POST.get('username', None)
  193. password = request.POST.get('password', None)
  194. user = authenticate(username=username, password=password)
  195. if user is None:
  196. message = ERROR_MESSAGE
  197. if u'@' in username:
  198. # Mistakenly entered e-mail address instead of username? Look it up.
  199. try:
  200. user = User.objects.get(email=username)
  201. except (User.DoesNotExist, User.MultipleObjectsReturned):
  202. message = _("Usernames cannot contain the '@' character.")
  203. else:
  204. if user.check_password(password):
  205. message = _("Your e-mail address is not your username."
  206. " Try '%s' instead.") % user.username
  207. else:
  208. message = _("Usernames cannot contain the '@' character.")
  209. return self.display_login_form(request, message)
  210. # The user data is correct; log in the user in and continue.
  211. else:
  212. if user.is_active and user.is_staff:
  213. login(request, user)
  214. # TODO: set last_login with an event.
  215. user.last_login = datetime.datetime.now()
  216. user.save()
  217. if request.POST.has_key('post_data'):
  218. post_data = _decode_post_data(request.POST['post_data'])
  219. if post_data and not post_data.has_key(LOGIN_FORM_KEY):
  220. # overwrite request.POST with the saved post_data, and continue
  221. request.POST = post_data
  222. request.user = user
  223. return self.root(request, request.path.split(self.root_path)[-1])
  224. else:
  225. request.session.delete_test_cookie()
  226. return http.HttpResponseRedirect(request.path)
  227. else:
  228. return self.display_login_form(request, ERROR_MESSAGE)
  229. login = never_cache(login)
  230. def index(self, request, extra_context=None):
  231. """
  232. Displays the main admin index page, which lists all of the installed
  233. apps that have been registered in this site.
  234. """
  235. app_dict = {}
  236. user = request.user
  237. for model, model_admin in self._registry.items():
  238. app_label = model._meta.app_label
  239. has_module_perms = user.has_module_perms(app_label)
  240. if has_module_perms:
  241. perms = {
  242. 'add': model_admin.has_add_permission(request),
  243. 'change': model_admin.has_change_permission(request),
  244. 'delete': model_admin.has_delete_permission(request),
  245. }
  246. # Check whether user has any perm for this module.
  247. # If so, add the module to the model_list.
  248. if True in perms.values():
  249. model_dict = {
  250. 'name': capfirst(model._meta.verbose_name_plural),
  251. 'admin_url': mark_safe('%s/%s/' % (app_label, model.__name__.lower())),
  252. 'perms': perms,
  253. }
  254. if app_label in app_dict:
  255. app_dict[app_label]['models'].append(model_dict)
  256. else:
  257. app_dict[app_label] = {
  258. 'name': app_label.title(),
  259. 'has_module_perms': has_module_perms,
  260. 'models': [model_dict],
  261. }
  262. # Sort the apps alphabetically.
  263. app_list = app_dict.values()
  264. app_list.sort(lambda x, y: cmp(x['name'], y['name']))
  265. # Sort the models alphabetically within each app.
  266. for app in app_list:
  267. app['models'].sort(lambda x, y: cmp(x['name'], y['name']))
  268. context = {
  269. 'title': _('Site administration'),
  270. 'app_list': app_list,
  271. 'root_path': self.root_path,
  272. }
  273. context.update(extra_context or {})
  274. return render_to_response(self.index_template or 'admin/index.html', context,
  275. context_instance=template.RequestContext(request)
  276. )
  277. index = never_cache(index)
  278. def display_login_form(self, request, error_message='', extra_context=None):
  279. request.session.set_test_cookie()
  280. if request.POST and request.POST.has_key('post_data'):
  281. # User has failed login BUT has previously saved post data.
  282. post_data = request.POST['post_data']
  283. elif request.POST:
  284. # User's session must have expired; save their post data.
  285. post_data = _encode_post_data(request.POST)
  286. else:
  287. post_data = _encode_post_data({})
  288. context = {
  289. 'title': _('Log in'),
  290. 'app_path': request.path,
  291. 'post_data': post_data,
  292. 'error_message': error_message,
  293. 'root_path': self.root_path,
  294. }
  295. context.update(extra_context or {})
  296. return render_to_response(self.login_template or 'admin/login.html', context,
  297. context_instance=template.RequestContext(request)
  298. )
  299. # This global object represents the default admin site, for the common case.
  300. # You can instantiate AdminSite in your own code to create a custom admin site.
  301. site = AdminSite()