Adding a Log entry for an action by a user in a Django App

巧了我就是萌 提交于 2020-01-22 07:09:42

问题


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 ?


回答1:


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)


来源:https://stackoverflow.com/questions/7905106/adding-a-log-entry-for-an-action-by-a-user-in-a-django-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!