django-auditlog/auditlog/receivers.py
2013-10-20 15:25:48 +02:00

57 lines
1.7 KiB
Python

import json
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.
Direct use is discouraged, connect your model through auditlog.registry.registry instead.
"""
if created:
changes = model_instance_diff(None, instance)
log_entry = LogEntry.objects.log_create(
instance,
action=LogEntry.Action.CREATE,
changes=json.dumps(changes),
)
log_entry.save()
def log_update(sender, instance, **kwargs):
"""
Signal receiver that creates a log entry when a model instance is changed and saved to the database.
Direct use is discouraged, connect your model through auditlog.registry.registry instead.
"""
if instance.pk is not None:
old = sender.objects.get(pk=instance.pk)
new = instance
changes = model_instance_diff(old, new)
log_entry = LogEntry.objects.log_create(
instance,
action=LogEntry.Action.UPDATE,
changes=json.dumps(changes),
)
log_entry.save()
def log_delete(sender, instance, **kwargs):
"""
Signal receiver that creates a log entry when a model instance is deleted from the database.
Direct use is discouraged, connect your model through auditlog.registry.registry instead.
"""
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),
)
log_entry.save()