Custom Django Admin Actions
Tags: django, python, djangoadmin, webdev
Published: 2023-01-19 13:58:54

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'
```
**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)
```
Now let's add some data to our database:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vsubkc3a4mczhzb5ikds.png)

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)
```

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
```
The final result is like below:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aq3awt3rpi5tu92lt6kz.png)

The complete source code is available [here](https://github.com/sevdimali/admin-custom-action).

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