<a id="custom-bulk-actions"></a>

# 添加自定义批量操作

本文介绍如何向不同的列表页添加自定义批量操作。

## 注册自定义批量操作

```python
from wagtail.admin.views.bulk_action import BulkAction
from wagtail import hooks


@hooks.register("register_bulk_action")
class CustomDeleteBulkAction(BulkAction):
    display_name = _("Delete")
    aria_label = _("Delete selected objects")
    action_type = "delete"
    template_name = "/path/to/confirm_bulk_delete.html"
    models = [...]

    @classmethod
    def execute_action(cls, objects, **kwargs):
        for obj in objects:
            do_something(obj)
        # 返回已更新对象的数量
        return (
            num_parent_objects,
            num_child_objects,
        )
```

各属性含义如下：

- `display_name` - 用户界面中按钮上显示的标签
- `aria_label` - 应用于用户界面中按钮的 `aria-label` 属性
- `action_type` - 该操作的唯一标识符（批量操作的 URL 中需要使用）
- `template_name` - 确认模板的路径
- `models` - 该批量操作可作用于的模型列表
- `action_priority`（可选）- 用于决定按钮在按钮列表中位置的数字
- `classes`（可选）- 应用于用户界面中按钮的一组 CSS 类名

确认模板示例如下：

```html+django
<!-- /path/to/confirm_bulk_delete.html -->

{% extends 'wagtailadmin/bulk_actions/confirmation/base.html' %}
{% load i18n wagtailadmin_tags %}

{% block titletag %}{% blocktranslate trimmed count counter=items|length %}Delete 1 item{% plural %}Delete {{ counter }} items{% endblocktranslate %}{% endblock %}

{% block header %}
    {% trans "Delete" as del_str %}
    {% include "wagtailadmin/shared/header.html" with title=del_str icon="doc-empty-inverse" %}
{% endblock header %}

{% block items_with_access %}
        {% if items %}
        <p>{% trans "Are you sure you want to delete these items?" %}</p>
        <ul>
            {% for item in items %}
            <li>
                <a href="" target="_blank" rel="noreferrer">{{ item.item.title }}</a>
            </li>
            {% endfor %}
        </ul>
        {% endif %}
{% endblock items_with_access %}

{% block items_with_no_access %}

{% blocktranslate trimmed asvar no_access_msg count counter=items_with_no_access|length %}You don't have permission to delete this item{% plural %}You don't have permission to delete these items{% endblocktranslate %}
{% include './list_items_with_no_access.html' with items=items_with_no_access no_access_msg=no_access_msg %}

{% endblock items_with_no_access %}

{% block form_section %}
{% if items %}
    {% trans 'Yes, delete' as action_button_text %}
    {% trans "No, don't delete" as no_action_button_text %}
    {% include 'wagtailadmin/bulk_actions/confirmation/form.html' with action_button_class="serious" %}
{% else %}
    {% include 'wagtailadmin/bulk_actions/confirmation/go_back.html' %}
{% endif %}
{% endblock form_section %}
```

```html+django
<!-- ./list_items_with_no_access.html -->
{% extends 'wagtailadmin/bulk_actions/confirmation/list_items_with_no_access.html' %}
{% load i18n %}

{% block per_item %}
    {% if item.can_edit %}
    <a href="{% url 'wagtailadmin_pages:edit' item.item.id %}" target="_blank" rel="noreferrer">{{ item.item.title }}</a>
    {% else %}
    {{ item.item.title }}
    {% endif %}
{% endblock per_item %}
```

`execute_action` 类方法是批量操作正常工作唯一必须覆盖的方法。它接收一个对象列表作为唯一必需参数，以及一批关键字参数，后者可通过覆盖 `get_execution_context` 方法来提供。例如：

```python
@classmethod
def execute_action(cls, objects, **kwargs):
    # 这里的 kwargs 就是 get_execution_context 方法的输出
    user = kwargs.get("user", None)
    num_parent_objects, num_child_objects = 0, 0
    # 你可以逐对象执行操作，也可以使用 Django 的批量更新和删除方法批量执行
    for obj in objects:
        num_child_objects += obj.get_children().count()
        num_parent_objects += 1
        obj.delete(user=user)
        num_parent_objects += 1
    return num_parent_objects, num_child_objects
```

可以覆盖 `get_execution_context` 方法，为 `execute_action` 提供上下文。

```python
def get_execution_context(self):
    return {"user": self.request.user}
```

可以覆盖 `get_context_data` 方法，向确认模板传递额外的上下文。

```python
def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context["new_key"] = some_value
    return context
```

可以覆盖 `check_perm` 方法来检查某个对象是否具有某项权限。`check_perm` 返回 `False` 的对象会以键 `'items_with_no_access'` 出现在上下文中。

```python
def check_perm(self, obj):
    return obj.has_perm("some_perm")  # 返回 True 或 False
```

可以通过覆盖 `get_success_message` 方法自定义管理后台中显示的成功提示。

```python
def get_success_message(self, num_parent_objects, num_child_objects):
    return _(
        "{} objects, including {} child objects have been updated".format(
            num_parent_objects, num_child_objects
        )
    )
```

## 向页面浏览器添加批量操作

为页面创建自定义批量操作类时，请继承 `wagtail.admin.views.pages.bulk_actions.page_bulk_action.PageBulkAction`，而不是 `wagtail.admin.views.bulk_action.BulkAction`。

### 基本示例

```python
from wagtail.admin.views.pages.bulk_actions.page_bulk_action import PageBulkAction
from wagtail import hooks


@hooks.register("register_bulk_action")
class CustomPageBulkAction(PageBulkAction): ...
```

## 向图片列表页添加批量操作

为图片创建自定义批量操作类时，请继承 `wagtail.images.views.bulk_actions.image_bulk_action.ImageBulkAction`，而不是 `wagtail.admin.views.bulk_action.BulkAction`。

### 基本示例

```python
from wagtail.images.views.bulk_actions.image_bulk_action import ImageBulkAction
from wagtail import hooks


@hooks.register("register_bulk_action")
class CustomImageBulkAction(ImageBulkAction): ...
```

## 向文档列表页添加批量操作

为文档创建自定义批量操作类时，请继承 `wagtail.documents.views.bulk_actions.document_bulk_action.DocumentBulkAction`，而不是 `wagtail.admin.views.bulk_action.BulkAction`。

### 基本示例

```python
from wagtail.documents.views.bulk_actions.document_bulk_action import DocumentBulkAction
from wagtail import hooks


@hooks.register("register_bulk_action")
class CustomDocumentBulkAction(DocumentBulkAction): ...
```

## 向用户列表页添加批量操作

为用户创建自定义批量操作类时，请继承 `wagtail.users.views.bulk_actions.user_bulk_action.UserBulkAction`，而不是 `wagtail.admin.views.bulk_action.BulkAction`。

### 基本示例

```python
from wagtail.users.views.bulk_actions.user_bulk_action import UserBulkAction
from wagtail import hooks


@hooks.register("register_bulk_action")
class CustomUserBulkAction(UserBulkAction): ...
```

<a id="wagtailsnippets-custom-bulk-actions"></a>

## 向 Snippet 列表页添加批量操作

为 Snippet 创建自定义批量操作类时，请继承 `wagtail.snippets.bulk_actions.snippet_bulk_action.SnippetBulkAction`，
而不是 `wagtail.admin.views.bulk_action.BulkAction`。

### 基本示例

```python
from wagtail.snippets.bulk_actions.snippet_bulk_action import SnippetBulkAction
from wagtail import hooks


@hooks.register('register_bulk_action')
class CustomSnippetBulkAction(SnippetBulkAction):
    # ...
```

如果你希望只在某些 Snippet 上应用该操作，请覆盖操作类中的 `models` 列表。

```python
from wagtail.snippets.bulk_actions.snippet_bulk_action import SnippetBulkAction
from wagtail import hooks


@hooks.register("register_bulk_action")
class CustomSnippetBulkAction(SnippetBulkAction):
    models = [SnippetA, SnippetB]
    # ...
```
