WagtailWagtail

How to add buttons to ModelAdmin Index View in Wagtail CMS

Jan 23, 2019 · Updated: Jul 12, 2021 · by Tim Kamanin

By default, every object in ModelAdmin's Index View of Wagtail CMS gets two buttons: Edit and Delete. What if we want to add more buttons? Is that possible in Wagtail? My answer is yes, and it's easy! Follow me!

Let's add a "View" button

Let's assume we have Product class, and for this class, we have ProductAdmin class defined in admin.py:

from django.contrib.admin import ModelAdmin


class ProductAdmin(ModelAdmin):
    model = Product

If we want to add more buttons to the index view we need to extend the default ButtonHelper class.

Here's how you can extend one to add a view button to it, follow my comments to get the idea:

from wagtail.contrib.modeladmin.helpers import ButtonHelper


class ProductButtonHelper(ButtonHelper):

    # Define classes for our button, here we can set an icon for example
    view_button_classnames = ["button-small", "icon", "icon-site"]

    def view_button(self, obj):
        # Define a label for our button
        text = "View {}".format(self.verbose_name)
        return {
            "url": obj.get_absolute_url(),  # decide where the button links to
            "label": text,
            "classname": self.finalise_classname(self.view_button_classnames),
            "title": text,
        }

    def get_buttons_for_obj(
        self, obj, exclude=None, classnames_add=None, classnames_exclude=None
    ):
        """
        This function is used to gather all available buttons.
        We append our custom button to the btns list.
        """
        btns = super().get_buttons_for_obj(
            obj, exclude, classnames_add, classnames_exclude
        )
        if "view" not in (exclude or []):
            btns.append(self.view_button(obj))
        return btns

The last step is to add our custom ProductButtonHelper to ProductAdmin class:

class ProductAdmin(ProductModelAdmin):
    model = Product
    button_helper_class = ProductButtonHelper

Now go to your ProductAdmin index page, and you should now see three buttons for each object listed: Delete, Edit, and the new View Product.

Done!

Hey, if you've found this useful, please share the post to help other folks find it:

There's even more:

Subscribe for updates

  • via Twitter: @timonweb
  • old school RSS:
  • or evergreen email ↓ ↓ ↓