Django - Custom Admin Actions Logging

django, python

Solution

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()

Problem

All changes you do in Django Admin is logged in the table django_admin_table and you can also see your most recent changes in "Recent Actions". But when you write own "Admin Actions" and make changes through them nothing is being logged by default. Example: ``` def make_checked(modeladmin, request, queryset): queryset.update(checked = 1) make_checked.short_description = 'Mark selected products as checked' ``` My question is now if it's possible to log custom admin actions and if so, how?

Original source

Related problems