Skip to content

Instantly share code, notes, and snippets.

@malderete
Last active January 3, 2020 21:30
Show Gist options
  • Save malderete/4656933617d667f1b82ff0d591797bee to your computer and use it in GitHub Desktop.
Save malderete/4656933617d667f1b82ff0d591797bee to your computer and use it in GitHub Desktop.
Mixin to use django-auditlog with DRF
from django.db.models.signals import pre_save
from django.utils.functional import curry
from auditlog.middleware import threadlocal, AuditlogMiddleware
from auditlog.models import LogEntry
class SetUserForAuditMixin:
def should_active_signal(self, request):
return request.user.is_authenticated
def initial(self, request, *args, **kwargs):
"""
Overwritten method to set the pre_save signal of django-auditlog
if its activated
"""
super().initial(request, *args, **kwargs)
if hasattr(threadlocal, 'auditlog'): # django-auditlog middleware is enabled
signal_duid = threadlocal.auditlog['signal_duid']
if self.should_active_signal(request):
set_actor = curry(AuditlogMiddleware.set_actor, user=request.user,
signal_duid=signal_duid)
pre_save.connect(set_actor, sender=LogEntry,
dispatch_uid=signal_duid, weak=False)
def finalize_response(self, request, response, *args, **kwargs):
"""
Overwritten method to disconnect pre_save signal of django-auditlog
if it was connected before.
"""
response = super().finalize_response(request, response, *args, **kwargs)
if hasattr(threadlocal, 'auditlog'):
pre_save.disconnect(sender=LogEntry, dispatch_uid=threadlocal.auditlog['signal_duid'])
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment