How to return an rest_framework.response object from a django custom middleware class?

Adil Malik picture Adil Malik · Jan 28, 2015 · Viewed 22.4k times · Source

I am trying to write a middleware class that ensures that the user is logged in. But the problem is this middleware class will only be applicable to a small set of views and these views return a DRF's Response object rather then the HTTPResponse object and these views are also decorated using api_view.

So when I try to return a Response object from the middle ware class it raises this error.

 assert renderer, ".accepted_renderer not set on Response"
AssertionError: .accepted_renderer not set on Response

I've searched a bit on SO and I guess that the error is somehow related to api_view decorator. But I am confused on how to solve this problem.

Any help is appreciated. :)

Answer

Jordan picture Jordan · Mar 9, 2015

I've just recently hit this problem. This solution doesn't use the Django Rest Framework Response, but if your server just returns JSON this solution might work for you.

New in django 1.7 or greater is the JSONResponse response type.

https://docs.djangoproject.com/en/3.0/ref/request-response/#jsonresponse-objects

In the middleware you can return these responses without having all the "No accepted renderers" and "Response has no attribute encode" errors.

It's very similar format to the DRF Response

The import is as follows: from django.http import JsonResponse

And how you use it:

return JsonResponse({'error': 'Some error'}, status=401)

Hopefully this helps you out!