DEV Community

Cover image for Custom Django Admin Actions
sevdimali
sevdimali

Posted on

Custom Django Admin Actions

Django Admin Actions allows us to make bulk operations. The default one is the delete action.

Django allows us to create our custom actions.

For example, let’s think of a situation where we have a company model, and we regularly export data based on company types.

For this case, we will create our custom action and we will be able to export selected types of companies.

Let's start :)

As a first step, we will create our model and register it in admin.py:

models.py

from django.db import models

OPTIONS = (
    ('telco', 'Telecommunication'),
    ('log', 'Logistics'),
    ('agr', 'Agriculture'),
    ('aero', 'Aerospace'),
    ('pharm', 'Pharmaceutical'),
)


class Company(models.Model):
    name = models.CharField(max_length=255)
    company_type = models.CharField(max_length=15, choices=OPTIONS)
    founded = models.DateField(null=True, blank=True)
    status = models.BooleanField(default=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'Company'
        verbose_name_plural = 'Companies'
Enter fullscreen mode Exit fullscreen mode

admin.py

from django.contrib import admin

from core.models import Company


class CompanyAdmin(admin.ModelAdmin):

    list_display = ['name', 'company_type', 'founded', 'status']

    list_filter = ['company_type']


admin.site.register(Company, CompanyAdmin)
Enter fullscreen mode Exit fullscreen mode

Now let's add some data to our database:

Image description

Now we will modify our admin.py as below:

from django.contrib import admin
from django.http import HttpResponseRedirect

from core.models import Company


class CompanyAdmin(admin.ModelAdmin):

    @admin.action(description='Export')
    def export_objects(self, request, queryset):
        selected = queryset.values_list('pk', flat=True)
        return HttpResponseRedirect('/export/?ids=%s' % (
            ','.join(str(pk) for pk in selected),
        ))

    list_display = ['name', 'company_type', 'founded', 'status']

    actions = [export_objects]

    list_filter = ['company_type']


admin.site.register(Company, CompanyAdmin)
Enter fullscreen mode Exit fullscreen mode

In the above code, we created our action function(export_objects), here we get selected object’s ids from the queryset and passed them as a get parameter to our export URL.

Also in our CompanyAdmin class, we added a new action to actions.

actions = [export_objects]

So in this step, we have to create our export view and URL.

urls.py
from django.contrib import admin
from django.urls import path
from core.views import export

urlpatterns = [
path('admin/', admin.site.urls),
path('export/', export, name='export'),
]
views.py

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


def export(request):
    ids = request.GET.get('ids').split(',')
    qs = Company.objects.filter(id__in = ids)
    response = HttpResponse(content_type="application/json")
    serializers.serialize("json", qs, stream=response)
    return response
Enter fullscreen mode Exit fullscreen mode

The final result is like below:

Image description

The complete source code is available here.

Thanks for reading. I hope you enjoyed it ❤.
The post first appeared in my blog
Keep Learning..!

Top comments (0)