Solved: In order to allow non-dict objects to be serialized set the safe parameter to False.

This post is related to “Developing REST API using functions in DRF application views” , for all articles related to Django REST framework visit our page “Django and Django REST Framework”

When we tried to write the “get” function code for the “users” API i.e. http://127.0.0.1:8000/users/ using below code in helloproject/helloapp/views.py,

@csrf_exempt
def users(request):
    if request.method == 'GET':
        users = UserInfo.objects.all()
        serializer = UserInfoSerializer(users, many=True)
        return JsonResponse(serializer.data)

and then when we tried to access the JSON using http GET in browser by accessing URL http://127.0.0.1:8000/users/ , we got below error in browser,

TypeError at /users/

In order to allow non-dict objects to be serialized set the safe parameter to False.

Request Method: GET
Request URL: http://127.0.0.1:8000/users/
Django Version: 3.1
Exception Type: TypeError
Exception Value:

In order to allow non-dict objects to be serialized set the safe parameter to False.

Exception Location: /home/devlab/devlab/django/workspace_class_based_views/env/lib/python3.6/site-packages/django/http/response.py, line 561, in init
Python Executable: /home/devlab/devlab/django/workspace_class_based_views/env/bin/python
Python Version: 3.6.9
Python Path:

[‘/home/devlab/devlab/django/workspace_class_based_views’,
‘/usr/lib/python36.zip’,
‘/usr/lib/python3.6’,
‘/usr/lib/python3.6/lib-dynload’,
‘/home/devlab/devlab/django/workspace_class_based_views/env/lib/python3.6/site-packages’]

Solution :

Change below line from,

return JsonResponse(serializer.data)

to

return JsonResponse(serializer.data, safe=False)

So, the final view will look like,

@csrf_exempt
def users(request):
    if request.method == 'GET':
        users = UserInfo.objects.all()
        serializer = UserInfoSerializer(users, many=True)
        return JsonResponse(serializer.data, safe=False)

Leave a Comment