Created
November 13, 2024 05:40
-
-
Save ajinzrathod/0215b412996ecfbfdc64f5ce19305b27 to your computer and use it in GitHub Desktop.
This code snippet demonstrates how to create custom actions in Django Admin to perform bulk updates on selected records. Specifically, it includes actions to mark users as active or inactive by updating the is_active field. These actions are integrated into the admin dropdown menu, allowing for efficient management of multiple records at once.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib import admin | |
from django.contrib.auth.admin import UserAdmin | |
from .models import Account | |
from django.utils.translation import ngettext | |
from django.contrib import messages | |
class UserAdmin(admin.ModelAdmin): | |
actions = ('mark_as_active', 'mark_as_inactive') # Add your actions here | |
list_display = ( | |
"username", | |
"email", | |
full_name, | |
"is_active", | |
) | |
list_filter = ( | |
"is_staff", | |
"is_superuser", | |
) | |
def mark_as_active(self, request, queryset): | |
updated = queryset.update(is_active=True) # Bulk update | |
self.message_user( | |
request, | |
ngettext( | |
'%d User was successfully marked as Active.', | |
'%d Users were successfully marked as Active.', | |
updated, | |
) % updated, | |
messages.SUCCESS | |
) | |
def mark_as_inactive(self, request, queryset): | |
updated = queryset.update(is_active=False) # Bulk update | |
self.message_user( | |
request, | |
ngettext( | |
'%d User was successfully marked as Inactive.', | |
'%d Users were successfully marked as Inactive.', | |
updated, | |
) % updated, | |
messages.SUCCESS | |
) | |
admin.site.register(Account, AccountAdminConfig) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment