在Django应用中为用户的操作添加日志条目 [英] Adding a Log entry for an action by a user in a Django App
问题描述
我需要为用户通过django应用程序中的视图对数据库所做的更改创建日志条目。
我已启用django-admin模块,并且可以使用以下管理界面检索所做更改的日志:
从django.contrib.admin.models导入LogEntry
从django.contrib.contenttypes.models导入ContentType
最近操作= LogEntry。 objects.all()
最近动作中的每个对象:
打印'Action:',each.action_flag .__ str __()
print'Message:',each.object_repr
print'Table:',ContentType.objects.get(id = each.content_type_id).name
我想为其他用户使用django应用程序中的视图创建的其他用户执行的操作创建类似的日志条目。我该怎么做呢 ?
您非常亲密。您只需要创建新的 LogEntry
对象并保存即可。 LogEntry
在对象
上具有快捷功能,可以做到这一点。
<来自django.contrib.admin.models的pre>
导入LogEntry,添加,更改
LogEntry.objects.log_action(
user_id = request.user.id ,
content_type_id = ContentType.objects.get_for_model(model_object).pk,
object_id = object.id,
object_repr = unicode(object.title),
action_flag = ADDITION(如果创建)否则更改)
I need to create a log entry for changes made by a user to the database via the views in my django application.
I have enabled the django-admin module and I can retrieve the logs of the changes made using the admin interface like this:
from django.contrib.admin.models import LogEntry
from django.contrib.contenttypes.models import ContentType
recentActions = LogEntry.objects.all()
for each in recentActions:
print 'Action:', each.action_flag.__str__()
print 'Message:', each.object_repr
print 'Table:', ContentType.objects.get(id = each.content_type_id).name
I want to create similar log entries for actions done by other users using the views in my django application. How do I do this ?
You're very close. You just need to create new LogEntry
objects and save them. LogEntry
has a shortcut function on objects
to do this.
from django.contrib.admin.models import LogEntry, ADDITION, CHANGE
LogEntry.objects.log_action(
user_id=request.user.id,
content_type_id=ContentType.objects.get_for_model(model_object).pk,
object_id=object.id,
object_repr=unicode(object.title),
action_flag=ADDITION if create else CHANGE)
这篇关于在Django应用中为用户的操作添加日志条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!