[Django]-ContentNotRenderedError: The response content must be rendered before it can be accessed (Django Middleware)

6๐Ÿ‘

โœ…

If you really want to return a Response instance, you need to set some properties before returning it:

from rest_framework.renderers import JSONRenderer

class BlockMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
    
    def __call__(self, request):
        blocking_res = self.handle_blocking(request)
        if blocking_res:
            return blocking_res

        response = self.get_response(request)
        if throttles_left <= 0:
            response = Response(
               data='User is blocked due to exceeding throttles limit.',
               status=status.HTTP_403_FORBIDDEN
            )
            response.accepted_renderer = JSONRenderer()
            response.accepted_media_type = "application/json"
            response.renderer_context = {}
            response.render()
            return response
        else:
            return response

You need to do the same also in your handle_blocking implementation, for example:

from rest_framework.renderers import JSONRenderer
response = Response(
    data='User is blocked, please contact the support team.',
    status=status.HTTP_403_FORBIDDEN
)
response.accepted_renderer = JSONRenderer()
response.accepted_media_type = "application/json"
response.renderer_context = {}
response.render()
return response

These properties are generally set by the api_view decorator that cannot be used with middlewares, so you must set them manually.

๐Ÿ‘คAlain Bianchini

Leave a comment