django-auditlog/src/auditlog/receivers.py

64 lines
1.9 KiB
Python
Raw Normal View History

from __future__ import unicode_literals
2013-10-20 13:25:48 +00:00
import json
2013-10-20 13:25:48 +00:00
from auditlog.diff import model_instance_diff
from auditlog.models import LogEntry
def log_create(sender, instance, created, **kwargs):
"""
Signal receiver that creates a log entry when a model instance is first saved to the database.
2015-05-31 13:06:06 +00:00
Direct use is discouraged, connect your model through :py:func:`auditlog.registry.register` instead.
2013-10-20 13:25:48 +00:00
"""
if created:
changes = model_instance_diff(None, instance)
log_entry = LogEntry.objects.log_create(
instance,
action=LogEntry.Action.CREATE,
changes=json.dumps(changes),
)
def log_update(sender, instance, **kwargs):
"""
Signal receiver that creates a log entry when a model instance is changed and saved to the database.
2015-05-31 13:06:06 +00:00
Direct use is discouraged, connect your model through :py:func:`auditlog.registry.register` instead.
2013-10-20 13:25:48 +00:00
"""
if instance.pk is not None:
try:
old = sender.objects.get(pk=instance.pk)
except sender.DoesNotExist:
pass
else:
new = instance
changes = model_instance_diff(old, new)
# Log an entry only if there are changes
if changes:
log_entry = LogEntry.objects.log_create(
instance,
action=LogEntry.Action.UPDATE,
changes=json.dumps(changes),
)
2013-10-20 13:25:48 +00:00
def log_delete(sender, instance, **kwargs):
"""
Signal receiver that creates a log entry when a model instance is deleted from the database.
2015-05-31 13:06:06 +00:00
Direct use is discouraged, connect your model through :py:func:`auditlog.registry.register` instead.
2013-10-20 13:25:48 +00:00
"""
if instance.pk is not None:
changes = model_instance_diff(instance, None)
log_entry = LogEntry.objects.log_create(
instance,
action=LogEntry.Action.DELETE,
changes=json.dumps(changes),
)