Debian Codegraph @

django/contrib/admin/sites.py

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