In Django, you can create custom admin actions to perform bulk actions on selected objects in the Django admin interface. Here's a step-by-step guide on how to create a custom Django admin action:
Define Your Model: Make sure you have a Django model for which you want to create a custom admin action.
python# models.py
from django.db import models
class YourModel(models.Model):
# Your model fields
name = models.CharField(max_length=255)
# ... other fields
Define Your Admin Class: Create an admin class for your model and register it with the admin site.
python# admin.py
from django.contrib import admin
from .models import YourModel
class YourModelAdmin(admin.ModelAdmin):
list_display = ('name',) # Customize as needed
admin.site.register(YourModel, YourModelAdmin)
Create the Custom Admin Action: In your admin class, define the function for your custom action.
python# admin.py
from django.contrib import admin
from .models import YourModel
class YourModelAdmin(admin.ModelAdmin):
list_display = ('name',) # Customize as needed
actions = ['custom_action']
def custom_action(self, request, queryset):
# Your custom action logic here
selected_objects = queryset.count()
self.message_user(request, f'Custom action performed on {selected_objects} objects.')
admin.site.register(YourModel, YourModelAdmin)
In this example, the custom_action
function is the custom action you are creating. It takes two parameters: request
and queryset
. request
is the current request object, and queryset
is the set of objects selected in the admin interface.
Add the Action to the Admin Interface:
Add your custom action to the actions dropdown in the admin interface by adding it to the actions
attribute in your admin class.
python# admin.py
from django.contrib import admin
from .models import YourModel
class YourModelAdmin(admin.ModelAdmin):
list_display = ('name',) # Customize as needed
actions = ['custom_action']
def custom_action(self, request, queryset):
# Your custom action logic here
selected_objects = queryset.count()
self.message_user(request, f'Custom action performed on {selected_objects} objects.')
admin.site.register(YourModel, YourModelAdmin)
Run Your Development Server: Start your Django development server and go to the admin interface. Select the objects you want to perform the custom action on, choose your custom action from the "Action" dropdown, and click "Go."
That's it! You've created a custom Django admin action. Customize the custom_action
function with your specific logic for the bulk action you want to perform on selected objects.