ContentNotRenderedError while using django middleware

前端 未结 2 1867
逝去的感伤
逝去的感伤 2021-01-23 03:21

I used process_request and process_response functions in django middleware in order to log the requests before hitting the viewset. But, I get Internal Server Error. I don\'t

相关标签:
2条回答
  • 2021-01-23 04:02

    The problem is the return Response() in your middleware methods.

    If you return a response in the process_request method, then Django will not call the view. You probably don't want to return anything here.

    You should return a response from the process_response method. You probably want to return the original response from the view (response) here. If you return a different response (e.g. Response(...)), then Django will return this to the user instead of the response from the view.

    class MyMiddleware(): 
        def process_request(self, request): 
            print "xxxxx"
    
        def process_response(self, request, response): 
            print "xxxxx"
            return response
    

    See the Django docs for more information about what you should return from each middleware method.

    0 讨论(0)
  • 2021-01-23 04:28

    I fixed the issue. It's because the response object returned by process_response doesn't have actual response. I modified it to following and it worked.

    class MyMiddleware(): 
        def process_request( self, request ): 
            print "xxxxx"
            return None
        def process_response( self, request, response ): 
            print "xxxxx" 
            return response
    
    0 讨论(0)
提交回复
热议问题