Home » Django & REST Api » In order to allow non-dict objects to be serialized set the safe parameter to False – Fixed

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

When developing a Django REST API, you might encounter the error: “In order to allow non-dict objects to be serialized set the safe parameter to False.” This typically happens when you return a JSON response using JsonResponse(serializer.data) without specifying the safe parameter.

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 :

Solution:

To resolve this issue, modify the line of code from:

return JsonResponse(serializer.data)

to:

return JsonResponse(serializer.data, safe=False)

This tells Django that the returned data is not a dictionary, allowing it to be serialized properly.

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)

Why Does This Error Occur?

By default, Django’s JsonResponse expects a dictionary object, which is why the safe parameter is set to True. When dealing with non-dict data, like lists, setting safe=False is required to prevent errors.


Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment