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