Django: Get current user in model save

后端 未结 6 1611
既然无缘
既然无缘 2020-12-04 23:29

I want to get the currently logged in user (request.user) in the save method of models.py. I want to check the role of the user and see if it can p

6条回答
  •  孤城傲影
    2020-12-05 00:04

    I found a way to do that, it involves declaring a MiddleWare, though. Create a file called get_username.py inside your app, with this content:

    from threading import current_thread
    
    _requests = {}
    
    def get_username():
        t = current_thread()
        if t not in _requests:
             return None
        return _requests[t]
    
    class RequestMiddleware(object):
        def process_request(self, request):
            _requests[current_thread()] = request
    

    Edit your settings.py and add it to the MIDDLEWARE_CLASSES:

    MIDDLEWARE_CLASSES = (
        ...
        'yourapp.get_username.RequestMiddleware',
    )
    

    Now, in your save() method, you can get the current username like this:

    from get_username import get_username
    
    ...
    
    def save(self, *args, **kwargs):
        req = get_username()
        print "Your username is: %s" % (req.user)
    

提交回复
热议问题