View / Browse all Django Admin Recent Actions
From DjangoWeekly Blog

by Ankur Gupta

If you have used Django Admin Panel the below screenshot will look familiar.



On the right side you can see a listing of latest actions aka create, update, delete actions taken by the user. Wouldn't it be convenient to browse all the actions taken by users ?.

Where is this information stored ?.

Execute python manage.py dbshell you will be inside your database cli client, with the project's default database selected.
Execute select * from django_admin_log; ( I am using sqlite3 for the tutorial ).

sqlite> select * from django_admin_log;
1|1|CBSE|1|[{"added": {}}]|9|1|2016-12-07 15:23:39.916789
2|2|ICSE|1|[{"added": {}}]|9|1|2016-12-07 15:23:43.296926
3|3|IB|1|[{"added": {}}]|9|1|2016-12-07 15:23:49.387019
sqlite> 

django_admin_log is created as part of django admin panel models. Check contrib/admin/models.py. In class LogEntry check class Meta you can see db_table = 'django_admin_log'. So in django_admin_log table all entries reside.

Let us add the model to our admin panel for browsing all these entries.
Go inside your admin.py and add

from django.contrib import admin
from django.contrib.admin.models import LogEntry
admin.site.register(LogEntry)

You will now be able to browse all user actions.


However all entries are editable. Let us create a non-editable version.

class LogEntryAdmin(admin.ModelAdmin):
    readonly_fields = ('content_type',
        'user',
        'action_time',
        'object_id',
        'object_repr',
        'action_flag',
        'change_message'
    )

    def has_delete_permission(self, request, obj=None):
        return False

    def get_actions(self, request):
        actions = super(LogEntryAdmin, self).get_actions(request)
        del actions['delete_selected']
        return actions

ModelAdmin helps us override the default behaviour/UI of a model in context of the admin panel. First we have marked all fields as read only by adding them in readonly_fields. Django admin will not allow editing of these fields/columns. We over-ride the has_delete_permission method to return False, thus disabling the delete button at the bottom of the Details View page.

On the List View / where all entries are listed we have a dropdown allows users to delete any selected object/entry. We over-ride the `get_actions` method and remove the delete_selected actions/method from the actions. Now one can browse all the log entries but cannot delete them.



Ankur has coded and deployed numerous Python software over the last 10 years, at three venture funded startup and a fortune 10 company. He currently heads Numerate Labs. Djangoweekly is his side project with Django being his go to web framework.

Blog Categories