1. Curtis Maloney
  2. django-audittrail

Source

django-audittrail / audittrail / admin.py

from django.contrib import admin
from audittrail import models

from django.contrib.admin import SimpleListFilter

from django.contrib.auth.models import User
from django.db.models import Max

from django.conf import settings

RECENT_USERS = getattr(settings, 'AUDIT_RECENT_USERS', 20)

class RecentlyActiveUser(SimpleListFilter):
    title = 'Most Recently Active'
    parameter_name = 'user'

    def lookups(self, request, model_admin):
        return (
            (user.pk, user.get_full_name() or user.username)
            for user in User.objects.annotate(
                last_audit=Max('audit_events__created')
            ).filter(last_audit__isnull=False).order_by('-last_audit')[:RECENT_USERS]
        )

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(user__pk=self.value())

class AuditAdmin(admin.ModelAdmin):
    list_display = ('created', 'user', 'action', 'details',)
    list_filter = ('created', 'action', RecentlyActiveUser,)
    date_hierarchy = 'created'
    search_fields = ('user__username', 'user__first_name', 'user__last_name', 'action', 'details',)

admin.site.register(models.Audit, AuditAdmin)