我試圖讓中間件這會改變某些領域基於子域的用戶,等等Django和中間件,它使用request.user始終是匿名
唯一的問題是request.user總是作爲AnonymousUser在中間件內,但是在視圖內是正確的用戶。我已經在設置中使用了默認的身份驗證和會話中間件django。
也有同樣的問題在這裏:Django, request.user is always Anonymous User 但因爲我沒有使用不同的認證方法並不過分回答總的問題,之前我調用我自己的中間件Django的認證正在運行。
在使用DRF的情況下,有沒有辦法在中間件中獲取request.user?我會在這裏展示一些示例代碼:
class SampleMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
#This will be AnonymousUser. I need it to be the actual user making the request.
print (request.user)
def process_response(self, request, response):
return response
與process_request:
class SampleMiddleware(object):
def process_request(self, request):
#This will be AnonymousUser. I need it to be the actual user making the request.
print (request.user)
def process_response(self, request, response):
return response
謝謝!
喬丹
中間件的順序是非常重要的。確保身份驗證中間件在您的設置之前列出 – 2014-10-07 16:32:24
在django運行其默認設置後,我已將它包含在中間件的末尾。 (認證和會話) – Jordan 2014-10-07 16:33:44
你試過用[process_request](https://docs.djangoproject.com/en/dev/topics/http/middleware/#process-request)而不是process_view? – danihp 2014-10-07 16:57:17