Get current user log in signal in Django

后端 未结 6 1780
忘掉有多难
忘掉有多难 2021-02-05 10:01

I am just using the admin site in Django. I have 2 Django signals (pre_save and post_save). I would like to have the username of the current user. How would I do that? It does n

6条回答
  •  长发绾君心
    2021-02-05 10:29

    We can solve this problem using middleware classes. Create singleton class in where will be storing user variable.

    class Singleton(type):
        '''
            Singleton pattern requires for GetUser class
        '''
        def __init__(cls, name, bases, dicts):
            cls.instance = None
    
        def __call__(cls, *args, **kwargs):
            if cls.instance is None:
                cls.instance = super(Singleton, cls).__call__(*args, **kwargs)
            return cls.instance 
    
    
    class NotLoggedInUserException(Exception):
        '''
        '''
        def __init__(self, val='No users have been logged in'):
            self.val = val
            super(NotLoggedInUser, self).__init__()
    
        def __str__(self):
            return self.val
    
    class LoggedInUser(object):
        __metaclass__ = Singleton
    
        user = None
    
        def set_user(self, request):
            if request.user.is_authenticated():
                self.user = request.user
    
        @property
        def current_user(self):
            '''
                Return current user or raise Exception
            '''
            if self.user is None:
                raise NotLoggedInUserException()
            return self.user
    
        @property
        def have_user(self):
        return not user is None
    

    Create own middleware class that will be setting user for LoggedInUser instance,and insert out middleware after 'django.contrib.auth.middleware.AuthenticationMiddleware' in settings.py

    from useranytimeaccess import LoggedInUser
    class LoggedInUserMiddleware(object):
        '''
            Insert this middleware after django.contrib.auth.middleware.AuthenticationMiddleware
        '''
        def process_request(self, request):
            '''
                Returned None for continue request
            '''
            logged_in_user = LoggedInUser()
            logged_in_user.set_user(request)
            return None
    

    In signals import LoggedInUser class and get current user

    logged_in = LoggedInUser()
    user = logged_in.user
    

提交回复
热议问题