How To Add Custom Actions In Django Admin

Hi Guys,
Have you ever encountered the challenge of needing to modify the boolean values of a list of objects or execute actions on multiple objects in django admin without the need to handle them individually? In this lesson, we’ll guide you through the process of creating custom actions in Django Admin, offering a solution to streamline and simplify such tasks.

In this tutorial, we’ll be working with a model named ‘Blog.’ Our goal is to demonstrate how to efficiently modify the ‘is_visible‘ field for a list of objects, allowing you to toggle its value between True and False with ease.

Step 1:

Create your models. Example;

class Blogs(models.Model):
    title = models.CharField(max_length=200, blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    date_created = models.DateTimeField(auto_now_add=True)
    is_visible = models.BooleanField(default=False)
    
    def __str__(self) -> str:
        return f"{self.title}"

Do not forget to run migrations

python manage.py makemigrations
python manage.py migrate

Step 2

After creating your models. move to the admin.py file

├── blog
│   └── admin.py

In this file lets write our code for handling the custom actions

from django.contrib import admin
from blog.models import Blog


@admin.register(Blog)
class BlogAdmin(admin.ModelAdmin):
    list_display = ["id", "title", "is_visible",, "date_created"] # this is what you would like to display on each column on the table list
    actions = ["make_visible", "make_invisible"] # these are the additional actions you would like to add

    def make_visible(modeladmin, request, queryset):
        queryset.update(is_visible=True) # this takes the queryset and makes all in that list is_visible = True

    make_visible.short_description = "Mark selected as visible" # this is the description that will be showing on the dropdown

    def make_invisible(modeladmin, request, queryset):
        queryset.update(is_visible=False)

    make_invisible.short_description = "Mark selected as invisible"

after this lets start the server

python manage.py runserver

after running the server. move to your Django admin dashboard and go to the blog section at the top you should see this

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top