Skip to content

Instantly share code, notes, and snippets.

@stevelacey
Forked from mindlace/middleware.py
Last active May 10, 2024 15:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevelacey/23fcf8977dd03edac491 to your computer and use it in GitHub Desktop.
Save stevelacey/23fcf8977dd03edac491 to your computer and use it in GitHub Desktop.
UserstampMiddleware
# -*- coding: utf-8 -*-
from django.db.models import signals
from django.utils.functional import curry
from rest_framework import authentication
class UserstampMiddleware(object):
"""Add user created_by and updated_by foreign key refs to any model automatically.
Almost entirely taken from https://github.com/Atomidata/django-audit-log/blob/master/audit_log/middleware.py"""
def process_request(self, request):
if not request.method in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
try:
user = request.user
if not user.is_authenticated():
# try basic auth
auth = authentication.BasicAuthentication().authenticate(request)
user, _ = auth if auth else (None, None)
except (authentication.exceptions.AuthenticationFailed, KeyError):
user = None
func = curry(userstampable, user)
signals.pre_save.connect(func, dispatch_uid = (self.__class__, request), weak = False)
def process_response(self, request, response):
signals.pre_save.disconnect(dispatch_uid = (self.__class__, request))
return response
# -*- coding: utf-8 -*-
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from django.utils import timezone
@receiver(pre_save)
def timestampable(sender, instance, *args, **kwargs):
if hasattr(instance, 'created_at'):
if instance._state.adding and not instance.created_at:
instance.created_at = timezone.now().replace(microsecond=0)
if hasattr(instance, 'updated_at'):
if instance._state.adding or instance.is_dirty():
instance.updated_at = timezone.now().replace(microsecond=0)
# bound by UserstampMiddleware
def userstampable(user, sender, instance, **kwargs):
if hasattr(instance, 'created_by_id') and instance._state.adding:
instance.created_by = instance.created_by or user
if hasattr(instance, 'updated_by_id'):
instance.updated_by = user
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment