<commit_before>=============
Admin actions
=============

.. currentmodule:: django.contrib.admin

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
:mod:`django.contrib.auth` app:

.. image:: _images/admin-actions.png

.. warning::

    The "delete selected objects" action uses :meth:`QuerySet.delete()
    <django.db.models.query.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
    :meth:`.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 :ref:`object
    deletion <topics-db-queries-delete>`.

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::

    from django.db import models

    STATUS_CHOICES = [
        ('d', 'Draft'),
        ('p', 'Published'),
        ('w', 'Withdrawn'),
    ]

    class Article(models.Model):
        title = models.CharField(max_length=100)
        body = models.TextField()
        status = models.CharField(max_length=1, choices=STATUS_CHOICES)

        def __str__(self):
            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:

* The current :class:`ModelAdmin`
* An :class:`~django.http.HttpRequest` representing the current request,
* A :class:`~django.db.models.query.QuerySet` containing the set of
  objects selected by the user.

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

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

.. note::

    For the best performance, we're using the queryset's :ref:`update method
    <topics-db-queries-update>`. Other types of actions might need to deal
    with each object individually; in these cases we'd iterate over the
    queryset::

        for obj in queryset:
            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 giving the
``make_published`` function a ``short_description`` attribute::

    def make_published(modeladmin, request, queryset):
        queryset.update(status='p')
    make_published.short_description = "Mark selected stories as published"

.. note::

    This might look familiar; the admin's ``list_display`` option uses the
    same technique to provide human-readable descriptions for callback
    functions registered there, too.

Adding actions to the :class:`ModelAdmin`
-----------------------------------------

Next, we'll need to inform our :class:`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::

    from django.contrib import admin
    from myapp.models import Article

    def make_published(modeladmin, request, queryset):
        queryset.update(status='p')
    make_published.short_description = "Mark selected stories as published"

    class ArticleAdmin(admin.ModelAdmin):
        list_display = ['title', 'status']
        ordering = ['title']
        actions = [make_published]

    admin.site.register(Article, ArticleAdmin)

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

.. image:: _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
:meth:`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 :class:`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::

    class ArticleAdmin(admin.ModelAdmin):
        ...

        actions = ['make_published']

        def make_published(self, request, queryset):
            queryset.update(status='p')
        make_published.short_description = "Mark selected stories as published"

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 :class:`ModelAdmin` to look up the action as a method.

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

.. _custom-admin-action:

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

    from django.contrib import messages
    from django.utils.translation import ngettext

    class ArticleAdmin(admin.ModelAdmin):
        ...

        def make_published(self, request, queryset):
            updated = queryset.update(status='p')
            self.message_user(request, ngettext(
                '%d story was successfully marked as published.',
                '%d stories were successfully marked as published.',
                updated,
            ) % updated, messages.SUCCESS)

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

.. image:: _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 :class:`~django.http.HttpResponse`
(or subclass) from your action. For example, you might write a export function
that uses Django's :doc:`serialization functions </topics/serialization>` to
dump some selected objects as JSON::

    from django.core import serializers
    from django.http import HttpResponse

    def export_as_json(modeladmin, request, queryset):<commit_msg>Fixed #32232 -- Fixed typo in docs/ref/contrib/admin/actions.txt.<commit_after>=============
Admin actions
=============

.. currentmodule:: django.contrib.admin

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
:mod:`django.contrib.auth` app:

.. image:: _images/admin-actions.png

.. warning::

    The "delete selected objects" action uses :meth:`QuerySet.delete()
    <django.db.models.query.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
    :meth:`.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 :ref:`object
    deletion <topics-db-queries-delete>`.

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::

    from django.db import models

    STATUS_CHOICES = [
        ('d', 'Draft'),
        ('p', 'Published'),
        ('w', 'Withdrawn'),
    ]

    class Article(models.Model):
        title = models.CharField(max_length=100)
        body = models.TextField()
        status = models.CharField(max_length=1, choices=STATUS_CHOICES)

        def __str__(self):
            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:

* The current :class:`ModelAdmin`
* An :class:`~django.http.HttpRequest` representing the current request,
* A :class:`~django.db.models.query.QuerySet` containing the set of
  objects selected by the user.

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

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

.. note::

    For the best performance, we're using the queryset's :ref:`update method
    <topics-db-queries-update>`. Other types of actions might need to deal
    with each object individually; in these cases we'd iterate over the
    queryset::

        for obj in queryset:
            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 giving the
``make_published`` function a ``short_description`` attribute::

    def make_published(modeladmin, request, queryset):
        queryset.update(status='p')
    make_published.short_description = "Mark selected stories as published"

.. note::

    This might look familiar; the admin's ``list_display`` option uses the
    same technique to provide human-readable descriptions for callback
    functions registered there, too.

Adding actions to the :class:`ModelAdmin`
-----------------------------------------

Next, we'll need to inform our :class:`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::

    from django.contrib import admin
    from myapp.models import Article

    def make_published(modeladmin, request, queryset):
        queryset.update(status='p')
    make_published.short_description = "Mark selected stories as published"

    class ArticleAdmin(admin.ModelAdmin):
        list_display = ['title', 'status']
        ordering = ['title']
        actions = [make_published]

    admin.site.register(Article, ArticleAdmin)

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

.. image:: _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
:meth:`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 :class:`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::

    class ArticleAdmin(admin.ModelAdmin):
        ...

        actions = ['make_published']

        def make_published(self, request, queryset):
            queryset.update(status='p')
        make_published.short_description = "Mark selected stories as published"

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 :class:`ModelAdmin` to look up the action as a method.

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

.. _custom-admin-action:

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

    from django.contrib import messages
    from django.utils.translation import ngettext

    class ArticleAdmin(admin.ModelAdmin):
        ...

        def make_published(self, request, queryset):
            updated = queryset.update(status='p')
            self.message_user(request, ngettext(
                '%d story was successfully marked as published.',
                '%d stories were successfully marked as published.',
                updated,
            ) % updated, messages.SUCCESS)

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

.. image:: _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 :class:`~django.http.HttpResponse`
(or subclass) from your action. For example, you might write an export function
that uses Django's :doc:`serialization functions </topics/serialization>` to
dump some selected objects as JSON::

    from django.core import serializers
    from django.http import HttpResponse

    def export_as_json(modeladmin, request, queryset):
{'fraction_non_alphanumeric': 0.09955843391227553, 'fraction_numerical': 0.0007653812187224022, 'mean_word_length': 3.509158481550305, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1766036', 'n_tokens_mistral': 4361, 'n_tokens_neox': 4131, 'n_words': 2050}