Created
October 19, 2012 13:43
-
-
Save mindlace/3918300 to your computer and use it in GitHub Desktop.
Add user created/modified to every model
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
"""Add user created_by and modified_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""" | |
from django.db.models import signals | |
from django.utils.functional import curry | |
class WhodidMiddleware(object): | |
def process_request(self, request): | |
if not request.method in ('GET', 'HEAD', 'OPTIONS', 'TRACE'): | |
if hasattr(request, 'user') and request.user.is_authenticated(): | |
user = request.user | |
else: | |
user = None | |
mark_whodid = curry(self.mark_whodid, user) | |
signals.pre_save.connect(mark_whodid, dispatch_uid = (self.__class__, request,), weak = False) | |
def process_response(self, request, response): | |
signals.pre_save.disconnect(dispatch_uid = (self.__class__, request,)) | |
return response | |
def mark_whodid(self, user, sender, instance, **kwargs): | |
if not getattr(instance, 'created_by_id', None): | |
instance.created_by = user | |
if hasattr(instance,'modified_by_id'): | |
instance.modified_by = user |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can someone explain How to use above code?