Debian Codegraph @

django/contrib/admin/actions.py

raw
1 """
2 Built-in, globally-available admin actions.
3 """
4
5 from django.contrib import messages
6 from django.contrib.admin import helpers
7 from django.contrib.admin.decorators import action
8 from django.contrib.admin.utils import model_ngettext
9 from django.core.exceptions import PermissionDenied
10 from django.template.response import TemplateResponse
11 from django.utils.translation import gettext as _
12 from django.utils.translation import gettext_lazy
13
14
15 @action(
16 permissions=["delete"],
17 description=gettext_lazy("Delete selected %(verbose_name_plural)s"),
18 )
19 def delete_selected(modeladmin, request, queryset):
20 """
21 Default action which deletes the selected objects.
22
23 This action first displays a confirmation page which shows all the
24 deletable objects, or, if the user has no permission one of the related
25 childs (foreignkeys), a "permission denied" message.
26
27 Next, it deletes all selected objects and redirects back to the change list.
28 """
29 opts = modeladmin.model._meta
30 app_label = opts.app_label
31
32 # Populate deletable_objects, a data structure of all related objects that
33 # will also be deleted.
34 (
35 deletable_objects,
36 model_count,
37 perms_needed,
38 protected,
39 ) = modeladmin.get_deleted_objects(queryset, request)
40
41 # The user has already confirmed the deletion.
42 # Do the deletion and return None to display the change list view again.
43 if request.POST.get("post") and not protected:
44 if perms_needed:
45 raise PermissionDenied
46 n = len(queryset)
47 if n:
48 modeladmin.log_deletions(request, queryset)
49 modeladmin.delete_queryset(request, queryset)
50 modeladmin.message_user(
51 request,
52 _("Successfully deleted %(count)d %(items)s.")
53 % {"count": n, "items": model_ngettext(modeladmin.opts, n)},
54 messages.SUCCESS,
55 )
56 # Return None to display the change list page again.
57 return None
58
59 objects_name = model_ngettext(queryset)
60
61 if perms_needed or protected:
62 title = _("Cannot delete %(name)s") % {"name": objects_name}
63 else:
64 title = _("Delete multiple objects")
65
66 context = {
67 **modeladmin.admin_site.each_context(request),
68 "title": title,
69 "subtitle": None,
70 "objects_name": str(objects_name),
71 "deletable_objects": [deletable_objects],
72 "model_count": dict(model_count).items(),
73 "queryset": queryset,
74 "perms_lacking": perms_needed,
75 "protected": protected,
76 "opts": opts,
77 "action_checkbox_name": helpers.ACTION_CHECKBOX_NAME,
78 "media": modeladmin.media,
79 }
80
81 request.current_app = modeladmin.admin_site.name
82
83 # Display the confirmation page
84 return TemplateResponse(
85 request,
86 modeladmin.delete_selected_confirmation_template
87 or [
88 "admin/%s/%s/delete_selected_confirmation.html"
89 % (app_label, opts.model_name),
90 "admin/%s/delete_selected_confirmation.html" % app_label,
91 "admin/delete_selected_confirmation.html",
92 ],
93 context,
94 )