blog: Django Admin actions are simple and powerful.

Posted on 16 Jun 2009 under with tags: django, programming, admin

Django admin actions are a great new feature available in the development version which allows you to easily extend the admin interface for doing bulk actions.

The basic workflow for the django admin in the past has always been “Select an object, then change it.” — Now, we have the ability to do bulk edits, deletes or whatever custom utility floats our boat. The official documentation explains admin actions in extreme detail very well, but I will run through a quick example!

Sending out bulk emails to users using Django admin actions.

Within admin.py, we define our admin class and custom action

class ProfileAdmin(admin.ModelAdmin):
    actions = ['send_verify_email']

    def send_verify_email(self, request, queryset):
        """
        Loop through all objects the user has selected and call our custom function.
        """
        for obj in queryset:
            Profile.objects.send_verify_email(obj.user)

        self.message_user(request, "%s users were successfully emailed for re-verification" % len(queryset))

    send_verify_email.short_description = 'Verify Email Addresses'

To summarize the code, here’s what’s important:

  1. We have a list named `actions` in which we define any custom actions we have created.
  1. You can create your action outside of the ModelAdmin class, but since this one is only for the scope of my ProfileAdmin, I put it in the class.
  1. queryset is very powerful. You can loop through it, or do one-line mass edits, e.g: queryset.update(status=‘p’)
  1. Profile.objects.send_verify_email is simply a manager function I define elsewhere. You can do whatever you wish here.
  1. self.message_user displays the well-known notes within the django admin near the top after you have submitted data. Just a nice touch

And that’s it! With this and some code within my manager function, I can now send out bulk emails to my users with a few clicks. Of course, this is just a simple example and I totally recommend reading the admin actions documentation

Thanks for reading. How about leaving a comment?

blog comments powered by Disqus