2
0

actions.txt 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. =============
  2. Admin actions
  3. =============
  4. .. currentmodule:: django.contrib.admin
  5. The basic workflow of Django's admin is, in a nutshell, "select an object,
  6. then change it." This works well for a majority of use cases. However, if you
  7. need to make the same change to many objects at once, this workflow can be
  8. quite tedious.
  9. In these cases, Django's admin lets you write and register "actions" --
  10. functions that get called with a list of objects selected on the change list
  11. page.
  12. If you look at any change list in the admin, you'll see this feature in
  13. action; Django ships with a "delete selected objects" action available to all
  14. models. For example, here's the user module from Django's built-in
  15. :mod:`django.contrib.auth` app:
  16. .. image:: _images/admin-actions.png
  17. .. warning::
  18. The "delete selected objects" action uses :meth:`QuerySet.delete()
  19. <django.db.models.query.QuerySet.delete>` for efficiency reasons, which
  20. has an important caveat: your model's ``delete()`` method will not be
  21. called.
  22. If you wish to override this behavior, you can override
  23. :meth:`.ModelAdmin.delete_queryset` or write a custom action which does
  24. deletion in your preferred manner -- for example, by calling
  25. ``Model.delete()`` for each of the selected items.
  26. For more background on bulk deletion, see the documentation on :ref:`object
  27. deletion <topics-db-queries-delete>`.
  28. Read on to find out how to add your own actions to this list.
  29. Writing actions
  30. ===============
  31. The easiest way to explain actions is by example, so let's dive in.
  32. A common use case for admin actions is the bulk updating of a model. Imagine a
  33. news application with an ``Article`` model::
  34. from django.db import models
  35. STATUS_CHOICES = {
  36. "d": "Draft",
  37. "p": "Published",
  38. "w": "Withdrawn",
  39. }
  40. class Article(models.Model):
  41. title = models.CharField(max_length=100)
  42. body = models.TextField()
  43. status = models.CharField(max_length=1, choices=STATUS_CHOICES)
  44. def __str__(self):
  45. return self.title
  46. A common task we might perform with a model like this is to update an
  47. article's status from "draft" to "published". We could easily do this in the
  48. admin one article at a time, but if we wanted to bulk-publish a group of
  49. articles, it'd be tedious. So, let's write an action that lets us change an
  50. article's status to "published."
  51. Writing action functions
  52. ------------------------
  53. First, we'll need to write a function that gets called when the action is
  54. triggered from the admin. Action functions are regular functions that take
  55. three arguments:
  56. * The current :class:`ModelAdmin`
  57. * An :class:`~django.http.HttpRequest` representing the current request,
  58. * A :class:`~django.db.models.query.QuerySet` containing the set of
  59. objects selected by the user.
  60. Our publish-these-articles function won't need the :class:`ModelAdmin` or the
  61. request object, but we will use the queryset::
  62. def make_published(modeladmin, request, queryset):
  63. queryset.update(status="p")
  64. .. note::
  65. For the best performance, we're using the queryset's :ref:`update method
  66. <topics-db-queries-update>`. Other types of actions might need to deal
  67. with each object individually; in these cases we'd iterate over the
  68. queryset::
  69. for obj in queryset:
  70. do_something_with(obj)
  71. That's actually all there is to writing an action! However, we'll take one
  72. more optional-but-useful step and give the action a "nice" title in the admin.
  73. By default, this action would appear in the action list as "Make published" --
  74. the function name, with underscores replaced by spaces. That's fine, but we
  75. can provide a better, more human-friendly name by using the
  76. :func:`~django.contrib.admin.action` decorator on the ``make_published``
  77. function::
  78. from django.contrib import admin
  79. ...
  80. @admin.action(description="Mark selected stories as published")
  81. def make_published(modeladmin, request, queryset):
  82. queryset.update(status="p")
  83. .. note::
  84. This might look familiar; the admin's
  85. :attr:`~django.contrib.admin.ModelAdmin.list_display` option uses a similar
  86. technique with the :func:`~django.contrib.admin.display` decorator to
  87. provide human-readable descriptions for callback functions registered
  88. there, too.
  89. Adding actions to the :class:`ModelAdmin`
  90. -----------------------------------------
  91. Next, we'll need to inform our :class:`ModelAdmin` of the action. This works
  92. just like any other configuration option. So, the complete ``admin.py`` with
  93. the action and its registration would look like::
  94. from django.contrib import admin
  95. from myapp.models import Article
  96. @admin.action(description="Mark selected stories as published")
  97. def make_published(modeladmin, request, queryset):
  98. queryset.update(status="p")
  99. class ArticleAdmin(admin.ModelAdmin):
  100. list_display = ["title", "status"]
  101. ordering = ["title"]
  102. actions = [make_published]
  103. admin.site.register(Article, ArticleAdmin)
  104. That code will give us an admin change list that looks something like this:
  105. .. image:: _images/adding-actions-to-the-modeladmin.png
  106. That's really all there is to it! If you're itching to write your own actions,
  107. you now know enough to get started. The rest of this document covers more
  108. advanced techniques.
  109. Handling errors in actions
  110. --------------------------
  111. If there are foreseeable error conditions that may occur while running your
  112. action, you should gracefully inform the user of the problem. This means
  113. handling exceptions and using
  114. :meth:`django.contrib.admin.ModelAdmin.message_user` to display a user friendly
  115. description of the problem in the response.
  116. Advanced action techniques
  117. ==========================
  118. There's a couple of extra options and possibilities you can exploit for more
  119. advanced options.
  120. Actions as :class:`ModelAdmin` methods
  121. --------------------------------------
  122. The example above shows the ``make_published`` action defined as a function.
  123. That's perfectly fine, but it's not perfect from a code design point of view:
  124. since the action is tightly coupled to the ``Article`` object, it makes sense
  125. to hook the action to the ``ArticleAdmin`` object itself.
  126. You can do it like this::
  127. class ArticleAdmin(admin.ModelAdmin):
  128. ...
  129. actions = ["make_published"]
  130. @admin.action(description="Mark selected stories as published")
  131. def make_published(self, request, queryset):
  132. queryset.update(status="p")
  133. Notice first that we've moved ``make_published`` into a method and renamed the
  134. ``modeladmin`` parameter to ``self``, and second that we've now put the string
  135. ``'make_published'`` in ``actions`` instead of a direct function reference. This
  136. tells the :class:`ModelAdmin` to look up the action as a method.
  137. Defining actions as methods gives the action more idiomatic access to the
  138. :class:`ModelAdmin` itself, allowing the action to call any of the methods
  139. provided by the admin.
  140. .. _custom-admin-action:
  141. For example, we can use ``self`` to flash a message to the user informing them
  142. that the action was successful::
  143. from django.contrib import messages
  144. from django.utils.translation import ngettext
  145. class ArticleAdmin(admin.ModelAdmin):
  146. ...
  147. def make_published(self, request, queryset):
  148. updated = queryset.update(status="p")
  149. self.message_user(
  150. request,
  151. ngettext(
  152. "%d story was successfully marked as published.",
  153. "%d stories were successfully marked as published.",
  154. updated,
  155. )
  156. % updated,
  157. messages.SUCCESS,
  158. )
  159. This make the action match what the admin itself does after successfully
  160. performing an action:
  161. .. image:: _images/actions-as-modeladmin-methods.png
  162. Actions that provide intermediate pages
  163. ---------------------------------------
  164. By default, after an action is performed the user is redirected back to the
  165. original change list page. However, some actions, especially more complex ones,
  166. will need to return intermediate pages. For example, the built-in delete action
  167. asks for confirmation before deleting the selected objects.
  168. To provide an intermediary page, return an :class:`~django.http.HttpResponse`
  169. (or subclass) from your action. For example, you might write an export function
  170. that uses Django's :doc:`serialization functions </topics/serialization>` to
  171. dump some selected objects as JSON::
  172. from django.core import serializers
  173. from django.http import HttpResponse
  174. def export_as_json(modeladmin, request, queryset):
  175. response = HttpResponse(content_type="application/json")
  176. serializers.serialize("json", queryset, stream=response)
  177. return response
  178. Generally, something like the above isn't considered a great idea. Most of the
  179. time, the best practice will be to return an
  180. :class:`~django.http.HttpResponseRedirect` and redirect the user to a view
  181. you've written, passing the list of selected objects in the GET query string.
  182. This allows you to provide complex interaction logic on the intermediary
  183. pages. For example, if you wanted to provide a more complete export function,
  184. you'd want to let the user choose a format, and possibly a list of fields to
  185. include in the export. The best thing to do would be to write a small action
  186. that redirects to your custom export view::
  187. from django.contrib.contenttypes.models import ContentType
  188. from django.http import HttpResponseRedirect
  189. def export_selected_objects(modeladmin, request, queryset):
  190. selected = queryset.values_list("pk", flat=True)
  191. ct = ContentType.objects.get_for_model(queryset.model)
  192. return HttpResponseRedirect(
  193. "/export/?ct=%s&ids=%s"
  194. % (
  195. ct.pk,
  196. ",".join(str(pk) for pk in selected),
  197. )
  198. )
  199. As you can see, the action is rather short; all the complex logic would belong
  200. in your export view. This would need to deal with objects of any type, hence
  201. the business with the ``ContentType``.
  202. Writing this view is left as an exercise to the reader.
  203. .. _adminsite-actions:
  204. Making actions available site-wide
  205. ----------------------------------
  206. .. method:: AdminSite.add_action(action, name=None)
  207. Some actions are best if they're made available to *any* object in the admin
  208. site -- the export action defined above would be a good candidate. You can
  209. make an action globally available using :meth:`AdminSite.add_action()`. For
  210. example::
  211. from django.contrib import admin
  212. admin.site.add_action(export_selected_objects)
  213. This makes the ``export_selected_objects`` action globally available as an
  214. action named "export_selected_objects". You can explicitly give the action
  215. a name -- good if you later want to programmatically :ref:`remove the action
  216. <disabling-admin-actions>` -- by passing a second argument to
  217. :meth:`AdminSite.add_action()`::
  218. admin.site.add_action(export_selected_objects, "export_selected")
  219. .. _disabling-admin-actions:
  220. Disabling actions
  221. -----------------
  222. Sometimes you need to disable certain actions -- especially those
  223. :ref:`registered site-wide <adminsite-actions>` -- for particular objects.
  224. There's a few ways you can disable actions:
  225. Disabling a site-wide action
  226. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  227. .. method:: AdminSite.disable_action(name)
  228. If you need to disable a :ref:`site-wide action <adminsite-actions>` you can
  229. call :meth:`AdminSite.disable_action()`.
  230. For example, you can use this method to remove the built-in "delete selected
  231. objects" action::
  232. admin.site.disable_action("delete_selected")
  233. Once you've done the above, that action will no longer be available
  234. site-wide.
  235. If, however, you need to reenable a globally-disabled action for one
  236. particular model, list it explicitly in your ``ModelAdmin.actions`` list::
  237. # Globally disable delete selected
  238. admin.site.disable_action("delete_selected")
  239. # This ModelAdmin will not have delete_selected available
  240. class SomeModelAdmin(admin.ModelAdmin):
  241. actions = ["some_other_action"]
  242. ...
  243. # This one will
  244. class AnotherModelAdmin(admin.ModelAdmin):
  245. actions = ["delete_selected", "a_third_action"]
  246. ...
  247. Disabling all actions for a particular :class:`ModelAdmin`
  248. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  249. If you want *no* bulk actions available for a given :class:`ModelAdmin`, set
  250. :attr:`ModelAdmin.actions` to ``None``::
  251. class MyModelAdmin(admin.ModelAdmin):
  252. actions = None
  253. This tells the :class:`ModelAdmin` to not display or allow any actions,
  254. including any :ref:`site-wide actions <adminsite-actions>`.
  255. Conditionally enabling or disabling actions
  256. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  257. .. method:: ModelAdmin.get_actions(request)
  258. Finally, you can conditionally enable or disable actions on a per-request
  259. (and hence per-user basis) by overriding :meth:`ModelAdmin.get_actions`.
  260. This returns a dictionary of actions allowed. The keys are action names, and
  261. the values are ``(function, name, short_description)`` tuples.
  262. For example, if you only want users whose names begin with 'J' to be able
  263. to delete objects in bulk::
  264. class MyModelAdmin(admin.ModelAdmin):
  265. ...
  266. def get_actions(self, request):
  267. actions = super().get_actions(request)
  268. if request.user.username[0].upper() != "J":
  269. if "delete_selected" in actions:
  270. del actions["delete_selected"]
  271. return actions
  272. .. _admin-action-permissions:
  273. Setting permissions for actions
  274. -------------------------------
  275. Actions may limit their availability to users with specific permissions by
  276. wrapping the action function with the :func:`~django.contrib.admin.action`
  277. decorator and passing the ``permissions`` argument::
  278. @admin.action(permissions=["change"])
  279. def make_published(modeladmin, request, queryset):
  280. queryset.update(status="p")
  281. The ``make_published()`` action will only be available to users that pass the
  282. :meth:`.ModelAdmin.has_change_permission` check.
  283. If ``permissions`` has more than one permission, the action will be available
  284. as long as the user passes at least one of the checks.
  285. Available values for ``permissions`` and the corresponding method checks are:
  286. - ``'add'``: :meth:`.ModelAdmin.has_add_permission`
  287. - ``'change'``: :meth:`.ModelAdmin.has_change_permission`
  288. - ``'delete'``: :meth:`.ModelAdmin.has_delete_permission`
  289. - ``'view'``: :meth:`.ModelAdmin.has_view_permission`
  290. You can specify any other value as long as you implement a corresponding
  291. ``has_<value>_permission(self, request)`` method on the ``ModelAdmin``.
  292. For example::
  293. from django.contrib import admin
  294. from django.contrib.auth import get_permission_codename
  295. class ArticleAdmin(admin.ModelAdmin):
  296. actions = ["make_published"]
  297. @admin.action(permissions=["publish"])
  298. def make_published(self, request, queryset):
  299. queryset.update(status="p")
  300. def has_publish_permission(self, request):
  301. """Does the user have the publish permission?"""
  302. opts = self.opts
  303. codename = get_permission_codename("publish", opts)
  304. return request.user.has_perm("%s.%s" % (opts.app_label, codename))
  305. The ``action`` decorator
  306. ========================
  307. .. function:: action(*, permissions=None, description=None)
  308. This decorator can be used for setting specific attributes on custom action
  309. functions that can be used with
  310. :attr:`~django.contrib.admin.ModelAdmin.actions`::
  311. @admin.action(
  312. permissions=["publish"],
  313. description="Mark selected stories as published",
  314. )
  315. def make_published(self, request, queryset):
  316. queryset.update(status="p")
  317. This is equivalent to setting some attributes (with the original, longer
  318. names) on the function directly::
  319. def make_published(self, request, queryset):
  320. queryset.update(status="p")
  321. make_published.allowed_permissions = ["publish"]
  322. make_published.short_description = "Mark selected stories as published"
  323. Use of this decorator is not compulsory to make an action function, but it
  324. can be useful to use it without arguments as a marker in your source to
  325. identify the purpose of the function::
  326. @admin.action
  327. def make_inactive(self, request, queryset):
  328. queryset.update(is_active=False)
  329. In this case it will add no attributes to the function.
  330. Action descriptions are %-formatted and may contain ``'%(verbose_name)s'``
  331. and ``'%(verbose_name_plural)s'`` placeholders, which are replaced,
  332. respectively, by the model's :attr:`~django.db.models.Options.verbose_name`
  333. and :attr:`~django.db.models.Options.verbose_name_plural`.