Admin actions

The basic workflow of Django’s admin is, in a nutshell, “select an object, then change it.” This works well for a majority of use cases. However, if you need to make the same change to many objects at once, this workflow can be quite tedious.

In these cases, Django’s admin lets you write and register “actions” – functions that get called with a list of objects selected on the change list page.

If you look at any change list in the admin, you’ll see this feature in action; Django ships with a “delete selected objects” action available to all models. For example, here’s the user module from Django’s built-in django.contrib.auth app:

../../../../_images/admin-actions.png

Warning

The “delete selected objects” action uses QuerySet.delete() for efficiency reasons, which has an important caveat: your model’s delete() method will not be called.

If you wish to override this behavior, you can override ModelAdmin.delete_queryset() or write a custom action which does deletion in your preferred manner – for example, by calling Model.delete() for each of the selected items.

For more background on bulk deletion, see the documentation on object deletion.

Read on to find out how to add your own actions to this list.

Writing actions

The easiest way to explain actions is by example, so let’s dive in.

A common use case for admin actions is the bulk updating of a model. Imagine a news application with an Article model:

  1. from django.db import models
  2. STATUS_CHOICES = [
  3. ('d', 'Draft'),
  4. ('p', 'Published'),
  5. ('w', 'Withdrawn'),
  6. ]
  7. class Article(models.Model):
  8. title = models.CharField(max_length=100)
  9. body = models.TextField()
  10. status = models.CharField(max_length=1, choices=STATUS_CHOICES)
  11. def __str__(self):
  12. return self.title

A common task we might perform with a model like this is to update an article’s status from “draft” to “published”. We could easily do this in the admin one article at a time, but if we wanted to bulk-publish a group of articles, it’d be tedious. So, let’s write an action that lets us change an article’s status to “published.”

Writing action functions

First, we’ll need to write a function that gets called when the action is triggered from the admin. Action functions are regular functions that take three arguments:

Our publish-these-articles function won’t need the ModelAdmin or the request object, but we will use the queryset:

  1. def make_published(modeladmin, request, queryset):
  2. queryset.update(status='p')

Note

For the best performance, we’re using the queryset’s update method. Other types of actions might need to deal with each object individually; in these cases we’d iterate over the queryset:

  1. for obj in queryset:
  2. do_something_with(obj)

That’s actually all there is to writing an action! However, we’ll take one more optional-but-useful step and give the action a “nice” title in the admin. By default, this action would appear in the action list as “Make published” – the function name, with underscores replaced by spaces. That’s fine, but we can provide a better, more human-friendly name by using the action() decorator on the make_published function:

  1. from django.contrib import admin
  2. ...
  3. @admin.action(description='Mark selected stories as published')
  4. def make_published(modeladmin, request, queryset):
  5. queryset.update(status='p')

Note

This might look familiar; the admin’s list_display option uses a similar technique with the display() decorator to provide human-readable descriptions for callback functions registered there, too.

Changed in Django 3.2:

The description argument to the action() decorator is equivalent to setting the short_description attribute on the action function directly in previous versions. Setting the attribute directly is still supported for backward compatibility.

Adding actions to the ModelAdmin

Next, we’ll need to inform our ModelAdmin of the action. This works just like any other configuration option. So, the complete admin.py with the action and its registration would look like:

  1. from django.contrib import admin
  2. from myapp.models import Article
  3. @admin.action(description='Mark selected stories as published')
  4. def make_published(modeladmin, request, queryset):
  5. queryset.update(status='p')
  6. class ArticleAdmin(admin.ModelAdmin):
  7. list_display = ['title', 'status']
  8. ordering = ['title']
  9. actions = [make_published]
  10. admin.site.register(Article, ArticleAdmin)

That code will give us an admin change list that looks something like this:

../../../../_images/adding-actions-to-the-modeladmin.png

That’s really all there is to it! If you’re itching to write your own actions, you now know enough to get started. The rest of this document covers more advanced techniques.

Handling errors in actions

If there are foreseeable error conditions that may occur while running your action, you should gracefully inform the user of the problem. This means handling exceptions and using django.contrib.admin.ModelAdmin.message_user() to display a user friendly description of the problem in the response.

Advanced action techniques

There’s a couple of extra options and possibilities you can exploit for more advanced options.

Actions as ModelAdmin methods

The example above shows the make_published action defined as a function. That’s perfectly fine, but it’s not perfect from a code design point of view: since the action is tightly coupled to the Article object, it makes sense to hook the action to the ArticleAdmin object itself.

You can do it like this:

  1. class ArticleAdmin(admin.ModelAdmin):
  2. ...
  3. actions = ['make_published']
  4. @admin.action(description='Mark selected stories as published')
  5. def make_published(self, request, queryset):
  6. queryset.update(status='p')

Notice first that we’ve moved make_published into a method and renamed the modeladmin parameter to self, and second that we’ve now put the string 'make_published' in actions instead of a direct function reference. This tells the ModelAdmin to look up the action as a method.

Defining actions as methods gives the action more idiomatic access to the ModelAdmin itself, allowing the action to call any of the methods provided by the admin.

For example, we can use self to flash a message to the user informing them that the action was successful:

  1. from django.contrib import messages
  2. from django.utils.translation import ngettext
  3. class ArticleAdmin(admin.ModelAdmin):
  4. ...
  5. def make_published(self, request, queryset):
  6. updated = queryset.update(status='p')
  7. self.message_user(request, ngettext(
  8. '%d story was successfully marked as published.',
  9. '%d stories were successfully marked as published.',
  10. updated,
  11. ) % updated, messages.SUCCESS)

This make the action match what the admin itself does after successfully performing an action:

../../../../_images/actions-as-modeladmin-methods.png

Actions that provide intermediate pages

By default, after an action is performed the user is redirected back to the original change list page. However, some actions, especially more complex ones, will need to return intermediate pages. For example, the built-in delete action asks for confirmation before deleting the selected objects.

To provide an intermediary page, return an HttpResponse (or subclass) from your action. For example, you might write an export function that uses Django’s serialization functions to dump some selected objects as JSON:

  1. from django.core import serializers
  2. from django.http import HttpResponse
  3. def export_as_json(modeladmin, request, queryset):
  4. response = HttpResponse(content_type="application/json")
  5. serializers.serialize("json", queryset, stream=response)
  6. return response

Generally, something like the above isn’t considered a great idea. Most of the time, the best practice will be to return an HttpResponseRedirect and redirect the user to a view you’ve written, passing the list of selected objects in the GET query string. This allows you to provide complex interaction logic on the intermediary pages. For example, if you wanted to provide a more complete export function, you’d want to let the user choose a format, and possibly a list of fields to include in the export. The best thing to do would be to write a small action that redirects to your custom export view:

  1. from django.contrib.contenttypes.models import ContentType
  2. from django.http import HttpResponseRedirect
  3. def export_selected_objects(modeladmin, request, queryset):
  4. selected = queryset.values_list('pk', flat=True)
  5. ct = ContentType.objects.get_for_model(queryset.model)
  6. return HttpResponseRedirect('/export/?ct=%s&ids=%s' % (
  7. ct.pk,
  8. ','.join(str(pk) for pk in selected),
  9. ))

As you can see, the action is rather short; all the complex logic would belong in your export view. This would need to deal with objects of any type, hence the business with the ContentType.

Writing this view is left as an exercise to the reader.

Making actions available site-wide

AdminSite.``add_action(action, name=None)

Some actions are best if they’re made available to any object in the admin site – the export action defined above would be a good candidate. You can make an action globally available using AdminSite.add_action(). For example:

  1. from django.contrib import admin
  2. admin.site.add_action(export_selected_objects)

This makes the export_selected_objects action globally available as an action named “export_selected_objects”. You can explicitly give the action a name – good if you later want to programmatically remove the action – by passing a second argument to AdminSite.add_action():

  1. admin.site.add_action(export_selected_objects, 'export_selected')

Disabling actions

Sometimes you need to disable certain actions – especially those registered site-wide – for particular objects. There’s a few ways you can disable actions:

Disabling a site-wide action

AdminSite.``disable_action(name)

If you need to disable a site-wide action you can call AdminSite.disable_action().

For example, you can use this method to remove the built-in “delete selected objects” action:

  1. admin.site.disable_action('delete_selected')

Once you’ve done the above, that action will no longer be available site-wide.

If, however, you need to re-enable a globally-disabled action for one particular model, list it explicitly in your ModelAdmin.actions list:

  1. # Globally disable delete selected
  2. admin.site.disable_action('delete_selected')
  3. # This ModelAdmin will not have delete_selected available
  4. class SomeModelAdmin(admin.ModelAdmin):
  5. actions = ['some_other_action']
  6. ...
  7. # This one will
  8. class AnotherModelAdmin(admin.ModelAdmin):
  9. actions = ['delete_selected', 'a_third_action']
  10. ...

Disabling all actions for a particular ModelAdmin

If you want no bulk actions available for a given ModelAdmin, set ModelAdmin.actions to None:

  1. class MyModelAdmin(admin.ModelAdmin):
  2. actions = None

This tells the ModelAdmin to not display or allow any actions, including any site-wide actions.

Conditionally enabling or disabling actions

ModelAdmin.``get_actions(request)

Finally, you can conditionally enable or disable actions on a per-request (and hence per-user basis) by overriding ModelAdmin.get_actions().

This returns a dictionary of actions allowed. The keys are action names, and the values are (function, name, short_description) tuples.

For example, if you only want users whose names begin with ‘J’ to be able to delete objects in bulk:

  1. class MyModelAdmin(admin.ModelAdmin):
  2. ...
  3. def get_actions(self, request):
  4. actions = super().get_actions(request)
  5. if request.user.username[0].upper() != 'J':
  6. if 'delete_selected' in actions:
  7. del actions['delete_selected']
  8. return actions

Setting permissions for actions

Actions may limit their availability to users with specific permissions by wrapping the action function with the action() decorator and passing the permissions argument:

  1. @admin.action(permissions=['change'])
  2. def make_published(modeladmin, request, queryset):
  3. queryset.update(status='p')

The make_published() action will only be available to users that pass the ModelAdmin.has_change_permission() check.

If permissions has more than one permission, the action will be available as long as the user passes at least one of the checks.

Available values for permissions and the corresponding method checks are:

You can specify any other value as long as you implement a corresponding has_<value>_permission(self, request) method on the ModelAdmin.

For example:

  1. from django.contrib import admin
  2. from django.contrib.auth import get_permission_codename
  3. class ArticleAdmin(admin.ModelAdmin):
  4. actions = ['make_published']
  5. @admin.action(permissions=['publish'])
  6. def make_published(self, request, queryset):
  7. queryset.update(status='p')
  8. def has_publish_permission(self, request):
  9. """Does the user have the publish permission?"""
  10. opts = self.opts
  11. codename = get_permission_codename('publish', opts)
  12. return request.user.has_perm('%s.%s' % (opts.app_label, codename))

Changed in Django 3.2:

The permissions argument to the action() decorator is equivalent to setting the allowed_permissions attribute on the action function directly in previous versions. Setting the attribute directly is still supported for backward compatibility.

The action decorator

action(**, permissions=None, description=None*)

New in Django 3.2.

This decorator can be used for setting specific attributes on custom action functions that can be used with actions:

  1. @admin.action(
  2. permissions=['publish'],
  3. description='Mark selected stories as published',
  4. )
  5. def make_published(self, request, queryset):
  6. queryset.update(status='p')

This is equivalent to setting some attributes (with the original, longer names) on the function directly:

  1. def make_published(self, request, queryset):
  2. queryset.update(status='p')
  3. make_published.allowed_permissions = ['publish']
  4. make_published.short_description = 'Mark selected stories as published'

Use of this decorator is not compulsory to make an action function, but it can be useful to use it without arguments as a marker in your source to identify the purpose of the function:

  1. @admin.action
  2. def make_inactive(self, request, queryset):
  3. queryset.update(is_active=False)

In this case it will add no attributes to the function.