Adding a Log entry for an action by a user in a Django App(在 Django 应用程序中为用户的操作添加日志条目)
问题描述
我需要为用户通过我的 django 应用程序中的视图对数据库所做的更改创建一个日志条目.
I need to create a log entry for changes made by a user to the database via the views in my django application.
我已经启用了 django-admin 模块,我可以像这样检索使用管理界面所做的更改的日志:
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
我想为其他用户使用我的 django 应用程序中的视图执行的操作创建类似的日志条目.我该怎么做呢 ?
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 ?
推荐答案
你已经很接近了.您只需要创建新的 LogEntry 对象并保存它们.LogEntry 在 objects 上有一个快捷功能来执行此操作.
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 应用程序中为用户的操作添加日志条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Django 应用程序中为用户的操作添加日志条目
基础教程推荐
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
