Created
December 31, 2019 11:31
-
-
Save vubon/a1b3b3777e795c6d36fcf7b1778d175b to your computer and use it in GitHub Desktop.
This file contains hidden or 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 functools import partial | |
from django.db.models import signals | |
class WhoDidMiddleware(object): | |
""" | |
his class represent as catch request user and mark the user into that model. | |
Usage: | |
MIDDLEWARE = [ | |
.... | |
'django.contrib.auth.middleware.AuthenticationMiddleware', | |
'who_created.middleware.WhoDidMiddleware', | |
.... | |
] | |
""" | |
def __init__(self, get_response): | |
self.get_response = get_response | |
def __call__(self, request): | |
if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'): | |
if hasattr(request, 'user') and request.user.is_authenticated: | |
user = request.user | |
else: | |
user = None | |
who_did = partial(self.who_did, user) | |
signals.pre_save.connect(who_did, dispatch_uid=(self.__class__, request,), weak=False) | |
response = self.get_response(request) | |
signals.pre_save.disconnect(dispatch_uid=(self.__class__, request,)) | |
return response | |
@staticmethod | |
def who_did(user, sender, instance, **kwargs): | |
""" | |
:param user: | |
:param sender: | |
:param instance: | |
:param kwargs: | |
:return: | |
""" | |
if hasattr(instance, "modified_by_id"): | |
instance.modified_by = user | |
if not getattr(instance, 'created_by_id', None): | |
instance.created_by = user |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment