created by and updated by in django

Solutions on MaxInterview for created by and updated by in django by the best coders in the world

showing results for - "created by and updated by in django"
Lennart
25 Nov 2017
1"""Add user created_by and modified_by foreign key refs to any model automatically.
2   Almost entirely taken from https://github.com/Atomidata/django-audit-log/blob/master/audit_log/middleware.py"""
3from django.db.models import signals
4from django.utils.functional import curry
5
6class WhodidMiddleware(object):
7    def process_request(self, request):
8        if not request.method in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
9            if hasattr(request, 'user') and request.user.is_authenticated():
10                user = request.user
11            else:
12                user = None
13
14            mark_whodid = curry(self.mark_whodid, user)
15            signals.pre_save.connect(mark_whodid,  dispatch_uid = (self.__class__, request,), weak = False)
16
17    def process_response(self, request, response):
18        signals.pre_save.disconnect(dispatch_uid =  (self.__class__, request,))
19        return response
20
21    def mark_whodid(self, user, sender, instance, **kwargs):
22        if 'created_by' in instance._meta.fields and not instance.created_by:
23            instance.created_by = user
24        if 'modified_by' in instance._meta.fields:
25            instance.modified_by = user
26
similar questions
queries leading to this page
created by and updated by in django