Django Admin Actions

As most people who would care know, Django 1.1 was recently released. There wasn’t a whole lot in this release that I was exactly clamoring for, but I always welcome a rash of bug fixes and the occasional new feature. It’s certainly nothing to complain about when my favorite web framework reaches a new version, and obtains a bit more stability along the way. When I first read about customizable Administrative Actions I didn’t really care. I guess I didn’t really see how it’d affect me that much, if at all. Then the other day it hit me in the face like a ton of bricks.

I’m currently working on an online catalog application. It’s not quite a store, just a catalog where people can browse items, and then call in an order. Think of it just like your old school print catalogs, just this one’s a bit more convenient. I’m not going to get into why it’s not going to just be a store, it’s just not currently. So anyways, I’m asked to build this catalog, and I’m trucking right along with it. The customer in question however needs to be able to “feature” items on a semi-regular basis. Now I don’t really know how many they’re going to feature, how often, or anything of the sort. Still, I thought, if I had to ‘feature’ 10 different items, it’d be a real pain to do it manually. Thankfully Django 1.1 brought me a solution just in time with the customizable administrative actions. I was able to write the following function:

def feature_item(self, request, queryset):
count = 0
for x in queryset:
x.is_featured = True
count += 1

if count == 1:
message = "1 product was"
else:
message = "%s products were" % count
self.message_user(request, "%s successfully featured" % message)
feature_item.short_description = "Feature selected items"

That was placed in my ProductAdmin class in admin.py, and then all I needed was:

actions = ['feature_item']

a bit further down in my ProductAdmin. Now users can view their products, select a few of them, grab “Feature items” from a drop down box, and click “Go”. Presto, bunch of new items featured on their front page. They can also “unfeature” a bunch of items in the same fashion. Saves a bunch of time for me with how easy it was to write that, and a bunch of time for the user later on down the road. I definitely recommend reading the documentation to get a better understanding of the admin actions as well. It’s worth the read.