Horilla list views provide built-in bulk actions such as Bulk Update, Bulk Delete, and Export. However, some modules require additional actions to handle selected records more efficiently. Examples include assigning records to the current user, restoring deleted records, or merging multiple records.

Horilla CRM makes this possible through custom_bulk_actions. You can define a custom button directly in a list view, implement the required logic in an endpoint, or extend an existing list view without modifying its original code.

This guide explains how to add an Assign to Me bulk action to the Leads list view and how to introduce the same functionality through a Horilla extension app.

How Custom Bulk Actions Work

When a user selects records using the checkboxes in a list view, Horilla’s JavaScript tracks the selected record IDs. The selectedRecordIds(view_id) function provides access to those IDs.

The list_view.html template iterates over custom_bulk_actions and renders the corresponding buttons. When a user clicks a button, Horilla sends an HTMX request containing the selected IDs as selected_ids and the action name as action.

The custom endpoint processes the selected records and returns a response to refresh the list view. Bulk action buttons are displayed when records are selected.

1. Define a Custom Bulk Action

The custom_bulk_actions attribute on HorillaListView accepts a list of dictionaries. Each dictionary defines a button’s label, endpoint, HTTP method, icon, and other request settings.

For the Leads list view, add the following configuration:

from django.utils.functional import cached_property
from horilla.urls import reverse_lazy
from horilla.utils.html import escapejs
from horilla.utils.translation import gettext_lazy as _




class LeadListView(LoginRequiredMixin, HorillaListView):
    ...


    @cached_property
    def custom_bulk_actions(self):
        confirm_msg = escapejs(
            _("Assign the selected leads to yourself?")
        )
        return [
            {
                "name": "assign_to_me",
                "label": _("Assign to Me"),
                "url": reverse_lazy(
                    "leads:bulk_assign_to_me"
                ),
                "method": "post",
                "icon": "fa-user-check",
                "target": "#modalBox",
                "swap": "innerHTML",
                "trigger": "confirmed",
                "hx_click": (
                    f"hxConfirm(this,'{confirm_msg}')"
                ),
            }
        ]

Using cached_property is useful when the action configuration depends on the request or needs to be calculated only once per view instance.

The configuration supports the following keys:

  • name: A unique identifier for the action. It is also used to identify the button and is sent as the action parameter.
  • label: The text displayed on the button.
  • icon: The Font Awesome icon class.
  • url: The endpoint that handles the action.
  • method: The HTTP method, usually post.
  • target: The element that receives the HTMX response.
  • swap: The HTMX swap mode.
  • trigger and hx_click: Configure confirmation handling, such as using hxConfirm().
  • onclick: Calls a JavaScript function instead of making the default request.
  • after_request: JavaScript to execute after the request completes.
  • bg_color, text_color, border_color, and hover_*: Optional button styling properties.
  • handler: Specifies a method on the list view to handle the action instead of using a separate URL.

2. Implement the Bulk Action Endpoint

The endpoint receives the selected record IDs, checks the user’s permissions, updates the records, and returns a response that refreshes the list.

Create the following view:

import json


from django.contrib import messages
from django.utils.decorators import method_decorator


from horilla.auth.mixins import LoginRequiredMixin
from horilla.utils.decorators import htmx_required
from horilla.utils.translation import gettext_lazy as _
from horilla.views.generic import View
from horilla.web import ScriptResponse


from .models import Lead




@method_decorator(htmx_required, name="dispatch")
class BulkAssignToMeView(LoginRequiredMixin, View):
    def post(self, request, *args, **kwargs):
        record_ids = json.loads(
            request.POST.get("selected_ids", "[]")
        )


        if not record_ids:
            messages.error(
                request,
                _("No records selected.")
            )
            return ScriptResponse(
                close=True,
                status=200,
            )


        # Apply the appropriate record-level access
        # and change-permission restrictions here.
        leads = Lead.objects.filter(
            pk__in=record_ids
        )


        updated = leads.update(
            lead_owner=request.user
        )


        messages.success(
            request,
            _("%(n)s lead(s) assigned to you.")
            % {"n": updated},
        )


        return ScriptResponse(
            reload=True,
            extra=(
                "$('#unselect-all-btn-LeadList').click();"
            ),
            close=True,
            status=200,
        )

The endpoint parses the selected IDs and updates the matching leads by setting lead_owner to the current user. After the operation, it displays a success message, refreshes the list, and clears the selection.

Important: The example shows the basic update logic. In a real application, validate the submitted JSON, reject malformed or unexpected IDs, and enforce the relevant record-level access rules and change permissions before updating records. Authentication and HTMX validation alone do not establish permission to modify every submitted record.

Register the URL

Add a URL pattern for the endpoint in the appropriate application’s URL configuration:

path(
“bulk-assign-to-me/”,
views.BulkAssignToMeView.as_view(),
name=”bulk_assign_to_me”,
),

Make sure the URL is included under the leads namespace referenced by reverse_lazy().

Refresh the List After Processing

Horilla’s ScriptResponse allows the endpoint to return instructions to the client.

  • reload=True refreshes the list view.
  • close=True closes the modal.
  • extra runs additional JavaScript, such as clearing the selected records.

The selector #unselect-all-btn-LeadList is an example. Replace LeadList with the actual view ID used by your list view so that the correct selection is cleared.

3. Use a View Handler Instead of a Separate Endpoint

A custom bulk action does not always need a dedicated URL. For simple operations, you can use the handler key to call a method on the list view itself.

Define the action using a handler:

{
    "name": "assign_to_me",
    "label": "Assign to Me",
    "handler": "assign_selected",
    "icon": "fa-user-check",
}

Then implement the corresponding method:

def assign_selected(self, record_ids, request):
    # Validate permissions and update records.
    ...


    return ScriptResponse(
        reload=True,
        close=True,
        status=200,
    )

In this approach, Horilla’s list view handles the action dispatch, decodes the selected IDs, and passes them to the configured handler.

Use a handler when the operation is a straightforward action performed directly on selected records. A separate endpoint is more suitable when the action requires its own URL, a dedicated form, or a separate confirmation workflow.

4. Add a Custom Bulk Action Through an Extension App

Sometimes the list view belongs to another module, and modifying its source code is not desirable. Horilla’s extension mechanism allows you to add a custom bulk action without changing the original list view.

Create a ListExtension in your extension app:

from horilla.extension.list import ListExtension


class LeadListExtension(ListExtension):
    _inherit_list = (
        "horilla_crm.leads.views.core.LeadListView"
    )


    custom_bulk_actions_append = [
        {
            "name": "assign_to_me",
            "label": "Assign to Me",
            "url": "/leads/bulk-assign-to-me/",
            "method": "post",
            "icon": "fa-user-check",
        }
    ]

The _inherit_list attribute identifies the list view to extend, while custom_bulk_actions_append adds the new action to its existing custom_bulk_actions configuration.

This approach keeps custom functionality separate from the original module and makes it easier to maintain when the underlying application changes.

If you want to add the action to every list view, you can target the generic list view:

_inherit_list = (
“horilla.contrib.generics.views.list.HorillaListView”
)

Use this global extension carefully. An action that is appropriate for Leads may not be valid for other models, so the handler and endpoint must support every list view where the action appears.

5. Additional Configuration Tips

Control the built-in bulk actions

You can disable existing bulk actions when they are unnecessary:

bulk_update_option = False
bulk_delete_enabled = False
bulk_export_option = False

Use the appropriate setting for the list view and feature you want to disable.

Enable record selection

Custom bulk actions depend on record selection. If bulk_select_option = False, the list view does not display the checkboxes required for selecting records.

Open a modal

Set target to #modalBox when the endpoint returns a form or other modal content. This is useful for actions that require additional input before processing the selected records.

Always validate permissions

The presence of a bulk action button does not guarantee that a user is allowed to perform the operation. The server must validate access to every affected record and enforce the relevant change permissions.

Horilla provides a flexible way to add custom bulk actions to list views. By defining custom_bulk_actions, implementing an endpoint or view handler, and returning a suitable ScriptResponse, you can introduce actions such as Assign to Me, Restore, or Merge Selected.

For functionality that belongs to another module, ListExtension and custom_bulk_actions_append let you extend the existing list view without modifying its original implementation. This keeps customizations organized and makes them easier to maintain as Horilla evolves.

Share this article