您在Django Admin中执行的所有更改都记录在表django_admin_table中,您还可以在“最近操作”中查看最近的更改。
但是当您编写自己的“管理操作”并通过它们进行更改时,默认情况下不会记录任何内容。
示例:
def make_checked(modeladmin, request, queryset):
queryset.update(checked = 1)
make_checked.short_description = 'Mark selected products as checked'
我现在的问题是,是否可以记录自定义管理操作,如果可以,如何记录?
答案 0 :(得分:16)
查看管理员的LogEntry
模型,更重要的是LogEntryManager
。模型管理器提供了一个log_action
方法,可以很容易地添加自己的日志条目(这是未经测试但应该给你的想法):
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'
您可以看到logging being used in the normal django admin的一些示例。如果您只想为整个查询集添加一个LogEntry
,则可以手动执行(因为上面的log_entry
需要一组专门用于记录单个对象的参数):
l = LogEntry(user_id=request.user.id, actions_flag=CHANGE, change_message="...")
l.save()
答案 1 :(得分:1)
谢谢!经过一些细微的改变后,工作得很完美:
def make_checked(modeladmin, request, queryset):
queryset.update(checked = 1)
ct = ContentType.objects.get_for_model(queryset.model) # for_model --> get_for_model
for obj in queryset:
LogEntry.objects.log_action( # log_entry --> log_action
user_id = request.user.id,
content_type_id = ct.pk,
object_id = obj.pk,
object_repr = obj.title,
action_flag = CHANGE, # actions_flag --> action_flag
change_message = 'Changed checked.')
make_checked.short_description = 'Mark selected products as checked'
答案 2 :(得分:0)
实际上,现在有比接受的答案更简单的方法,前提是您有ModelAdmin
可用,在自定义操作的情况下也可以这样做。
ModelAdmin
类的文档尚不完善,但实际上它是provides these methods的快捷方式:
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.
"""
这些很容易使用。继续问题中的示例:
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'