While I am calling Django url, I get an error:
AssertionError: .accepted_renderer not set on Response.
My code is:
from rest_framework.response import Response
from rest_framework.decorators import api_view, renderer_classes
from rest_framework.renderers import JSONRenderer, TemplateHTMLRenderer
from myapp.models import employees
from .serializers import EmployeeSerializer
@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def getData(request):
employees = {'name':'Bill', 'location':'Kolkata' }
return Response(employees)
def getEmployees(request):
employee_list = employees.objects.all()
serializer = EmployeeSerializer(employee_list, many = True)
return Response(serializer.data)
CodePudding user response:
This error typically indicates that you are trying to return a response from your Django view that has not been rendered by a renderer. In Django, renderers are used to convert the data in a response into a format that can be returned to the client, such as JSON or XML.
To fix this error, you will need to specify a renderer for the response. You can do this by setting the .accepted_renderer attribute on the response object, or by using the @api_view decorator and specifying the renderer in the renderer_classes argument.
Here is an example of how to use the @api_view decorator to specify a renderer for a Django view:
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer
@api_view(["GET"], renderer_classes=[JSONRenderer])
def my_view(request):
data = {"hello": "world"}
return Response(data)
In this example, the @api_view decorator is used to specify that the view should only accept GET requests, and that the response should be rendered using the JSONRenderer class. This will ensure that the response is properly formatted before it is returned to the client.
[This was answered by OpenAPI]
CodePudding user response:
It should not be any line spaces between @api_view
decorators and the views getData
and getEmployee
should have its individual decorators too
@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def getData(request):
employees = {'name':'Bill', 'location':'Kolkata' }
return Response(employees)
@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def getEmployees(request):
employee_list = employees.objects.all()
serializer = EmployeeSerializer(employee_list, many = True)
return Response(serializer.data)