Last active
January 3, 2020 21:30
-
-
Save malderete/4656933617d667f1b82ff0d591797bee to your computer and use it in GitHub Desktop.
Mixin to use django-auditlog with DRF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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