Django Admin的日志管理

2023-04-11 00:00:00 django 管理 日志

Django Admin提供了一个自动记录管理后台操作的日志工具。默认情况下,管理日志模型是禁用的,需要通过在模型文件中导入和注册Django Admin日志模型来启用。

步骤:

  1. 在models.py中导入和注册Django Admin日志模型:
from django.contrib.admin.models import LogEntry, ADDITION, CHANGE, DELETION

class MyModel(models.Model):
    # model fields here

admin.site.register(MyModel)

@admin.register(LogEntry)
class LogEntryAdmin(admin.ModelAdmin):
    list_display = ['__str__', 'user', 'action_time', 'content_type', 'object_id', 'object_repr', 'action_flag', 'change_message']
    list_filter = ['action_time', 'user', 'content_type', 'action_flag']
    search_fields = ['object_repr', 'change_message', 'user__username']
  1. 在admin.py文件中注册MyModel以获取访问管理日志的权限:
from django.contrib import admin
from .models import MyModel

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    pass
  1. 运行Migrations以创建LogEntry模型的数据库表:
python manage.py makemigrations
python manage.py migrate
  1. 登录到Django Admin,在左侧导航栏中选择“Log Entry”选项卡,您将看到添加,更改和删除操作的详细信息,如下所示:

Django Admin日志

您可以通过过滤器和搜索栏过滤结果,并对actions select框进行比对。另外,您还可以使用LogEntry对象的方法轻松检查详细信息,如下所示:

log = LogEntry.objects.get(...)
log.user  # User object
log.action_time  # datetime
log.content_type  # ContentType object
log.object_id  # string (or None)
log.object_repr  # string (or None)
log.action_flag  # integer (ADDITION, CHANGE, DELETION)
log.change_message  # string (or None)

注:代码示例:

from django.db import models
from django.contrib.auth.models import User
from django.contrib.admin.models import LogEntry, ADDITION, CHANGE, DELETION
from django.contrib.contenttypes.models import ContentType
from django.contrib import admin

class MyModel(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

admin.site.register(MyModel)

from django.utils.html import escape
from django.utils.safestring import mark_safe
class LogEntryAdmin(admin.ModelAdmin):
    date_hierarchy = 'action_time'

    readonly_fields = LogEntry._meta.get_fields()

    list_filter = [
        ('content_type', admin.RelatedOnlyFieldListFilter),
        'action_flag',
        'user',
    ]

    search_fields = [
        'object_repr',
        'change_message',
        'user__first_name',
        'user__last_name',
        'user__username',
    ]

    list_display = [
        'action_time',
        '__str__',
        'user',
        'content_type',
        'action_flag',
        'change_message',
    ]

    def content_type(self, obj):
        content_type = ContentType.objects.get_for_id(obj.content_type_id)
        app_label = content_type.app_label
        model = content_type.model
        return mark_safe('<a href="{}">{}</a>'.format(
            reverse('admin:%s_%s_changelist' % (app_label, model), current_app=admin.site.name),
            escape(str(content_type)),
        ))

    def has_add_permission(self, request):
        return False

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

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

admin.site.register(LogEntry, LogEntryAdmin)

相关文章