Django: Get current user in model save

后端 未结 6 1612
既然无缘
既然无缘 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:06

    The solution proposed by @nKn is good starting point, but when I tried to implemented today, I faced two issues:

    1. In the current Django version middleware created as plain object doesn't work.
    2. Unittests are failing (since they usually run in single thread, so your 'request' will can be sticked between two consequent tests if the first test has HTTP-request and the second hasn't).

    Here is my updated middleware code, which works with Django 1.10 and doesn't break unittests:

    from threading import current_thread
    
    from django.utils.deprecation import MiddlewareMixin
    
    
    _requests = {}
    
    
    def current_request():
        return _requests.get(current_thread().ident, None)
    
    
    class RequestMiddleware(MiddlewareMixin):
    
        def process_request(self, request):
            _requests[current_thread().ident] = request
    
        def process_response(self, request, response):
            # when response is ready, request should be flushed
            _requests.pop(current_thread().ident, None)
            return response
    
        def process_exception(self, request, exception):
            # if an exception has happened, request should be flushed too
             _requests.pop(current_thread().ident, None)
    

提交回复
热议问题