Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

created by and updated by in django

"""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 'created_by' in instance._meta.fields and not instance.created_by:
            instance.created_by = user
        if 'modified_by' in instance._meta.fields:
            instance.modified_by = user
Comment

PREVIOUS NEXT
Code Example
Python :: add title to tkinter window python 
Python :: how to create dynamic list in python 
Python :: how to write a function in python 
Python :: normalize a group in countplot 
Python :: python search a string in another string get last result 
Python :: python run linux command and get output 
Python :: binary search tree in python 
Python :: project euler problem 11 python 
Python :: decimal to binary 
Python :: python how to exit function 
Python :: how to run class.function from name python 
Python :: assignment operators in python 
Python :: circular dependencies in python 
Python :: .translate python 
Python :: list count python 
Python :: argparse type 
Python :: cv2 assertion failed 
Python :: django login required as admin 
Python :: Python NumPy insert Function Example Working with arrays 
Python :: open file in python network url 
Python :: double underscore methods python 
Python :: django make new application folder 
Python :: Python NumPy expand_dims Function Example 
Python :: mean squared error in machine learning formula 
Python :: plt.hist bins 
Python :: python selenium driver 
Python :: python - input: integer 
Python :: for loop in python 
Python :: replace nan from another column 
Python :: describe in python 
ADD CONTENT
Topic
Content
Source link
Name
7+4 =