Django - Custom Admin Actions Logging

There's actually now a much easier way to do this than the accepted answer, provided you have a ModelAdmin available, which you do in the case of a custom action.

The ModelAdmin class is not well documented, but it actually provides these methods as shortcuts:

def log_addition(self, request, object, message):
    """
    Log that an object has been successfully added.

    The default implementation creates an admin LogEntry object.
    """

def log_change(self, request, object, message):
    """
    Log that an object has been successfully changed.

    The default implementation creates an admin LogEntry object.
    """

def log_deletion(self, request, object, object_repr):
    """
    Log that an object will be deleted. Note that this method must be
    called before the deletion.

    The default implementation creates an admin LogEntry object.
    """

These are easy enough to use. To continue with the example in the question:

def make_checked(modeladmin, request, queryset):
    queryset.update(checked = 1)
    for obj in queryset:
        modeladmin.log_change(request, obj, 'Marked checked: ' + str(obj))
make_checked.short_description = 'Mark selected products as checked'

Look at the admin's LogEntry model and more importantly the LogEntryManager. The model manager provides a log_action method which makes it easy to add your own log entries (this is untested but should give you the idea):

from django.contrib.admin.models import LogEntry, CHANGE
from django.contrib.contenttypes.models import ContentType

def make_checked(modeladmin, request, queryset):
    queryset.update(checked = 1)

    ct = ContentType.objects.get_for_model(queryset.model)
    for obj in queryset:
        LogEntry.objects.log_action(
            user_id=request.user.id, 
            content_type_id=ct.pk,
            object_id=obj.pk,
            object_repr=obj.description,
            action_flag=CHANGE,
            change_message="You have ...") 
make_checked.short_description = 'Mark selected products as checked'

You can see some examples of logging being used in the normal django admin. If you only wanted to add a single LogEntry for the entire queryset, you could do it manually (as the log_entry above expects a certain set of arguments tailored to logging individual objects):

l = LogEntry(user_id=request.user.id, actions_flag=CHANGE, change_message="...")
l.save()

Tags:

Python

Django