Customization: Custom admin actions

  1. Custom filters
  2. Customization

If we’re doing a more newspaper-style publication, we might want to be able to quickly set both the live and the date of the posts at the same time. While editable_fields makes it easy to change one field across multiple posts, they don’t let us perform more complex actions.

In the PostAdmin class, add a new method called “makePublic()”. This method will accept a list of postings and will set “live” to True and “date” to midnight on the morning of the current day. The method also requires two imports at the top of the file to help it along.

from django.template import Template, Context

from datetime import date

class PostAdmin(admin.ModelAdmin):

actions = ['makePublic']

def makePublic(self, request, chosenPostings):

today =

for post in chosenPostings: = True = today

#send notification to the admin

message = Template('{% load humanize %}Made {{ count|apnumber }} post{{ count|pluralize }} public as of {{ date }}')

messageContext = Context({'count':chosenPostings.count(), 'date': today})

messageText = message.render(messageContext)

self.message_user(request, messageText)

makePublic.short_description = 'Make selected posts public'

There are three parts to an admin action. First, the action must be listed in the list of “actions”. Second, the action needs a method in the ModelAdmin class. And third, the method needs a short description for use in the admin pages.

Django’s admin sends this method a “request” (the same kind we used already in views), as well as the list of postings that the editor has chosen. The method loops through each post, sets “live” and “date”, and then saves the post.

The largest part of the method provides feedback that the action was performed successfully. It creates a quick template so that we can more easily handle plurals and friendly numbers, creates a context for that template, and then renders it to the text that is pushed into the editor’s message queue.

Check the pull-down “action” menu on the Post administration page. It should now have a new option below “Delete selected posts”: “Make select posts public”.

  1. Custom filters
  2. Customization