Implementing auditing in Django models involves tracking changes made to model instances and storing this information in a separate auditing model. Here's a basic guide on how to implement auditing in Django models:
python# models.py
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
class AuditLog(models.Model):
action = models.CharField(max_length=10) # 'create', 'update', or 'delete'
user = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
details = models.TextField(blank=True)
# GenericForeignKey to associate audit log with any model
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
python# signals.py
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver
from .models import YourModel, AuditLog
@receiver(post_save, sender=YourModel)
def log_object_change(sender, instance, created, **kwargs):
action = 'create' if created else 'update'
details = 'Created' if created else 'Updated'
AuditLog.objects.create(
action=action,
user=instance.modified_by, # If you have a modified_by field in your model
content_type=ContentType.objects.get_for_model(instance),
object_id=instance.id,
details=details
)
@receiver(pre_delete, sender=YourModel)
def log_object_delete(sender, instance, **kwargs):
AuditLog.objects.create(
action='delete',
user=instance.modified_by, # If you have a modified_by field in your model
content_type=ContentType.objects.get_for_model(instance),
object_id=instance.id,
details='Deleted'
)
ready()
method of your app's apps.py
.python# apps.py
from django.apps import AppConfig
class YourAppConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'your_app'
def ready(self):
import your_app.signals # noqa
bashpython manage.py makemigrations
python manage.py migrate
With these steps, your Django models will now be audited, and changes made to model instances will be logged in the AuditLog
model. Make sure to adjust the implementation according to your specific requirements and models.