[Django]-How to resolve AssertionError: .accepted_renderer not set on Response in django and ajax

128👍

If you’re using a function based view, then this issue usually means you forgot to add the @api_view and the @renderer_classes decorator to your view.

Example:

from rest_framework.decorators import api_view, renderer_classes
from rest_framework.renderers import JSONRenderer, TemplateHTMLRenderer

@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def get_assessment_count(request):
    [...]
    data = {'count': queryset.count()}
    return Response(data, template_name='assessments.html')
👤Hybrid

19👍

If anyone has this issue with Django Rest Framework while using Response in a function based view, don’t forget to use @APIView instead of View decorator.

3👍

In addition to the accepted answer by @DavidLam it could also be that an error was thrown in your view/handler4xx/handler5xx and you’ve not caught it appropriately.

👤Marc

0👍

When developing web API you must use API decorator to handle request and generate responses, so you should use @api_view(['GET','POST']) before functions.

👤biniam

0👍

This could be due to overriding the dispatch method of a view or ViewSet. If you override that method and return without running the base/super version of the function, the renderer wont be setup on the response.

This is the line that sets the renderer on the response, in the source for APIView:

self.response = self.finalize_response(request, response, *args, **kwargs)

Leave a comment