You cannot call `.save()` after accessing `serializer.data`
Question:
Error Showing when post data from API
You cannot call `.save()` after accessing `serializer.data`.If you need to access data before committing to the database then inspect 'serializer.validated_data' instead.
My written Code is:
serializerdata = serializers.CreateSerializer(data=request.data)
if serializerdata.is_valid():
user_id = serializerdata.data.get('user_id')
if user_id==2:
serializerdata.save(i_created_by=request.user)
return JsonResponse({"message": "success"})
else:
return JsonResponse({"message": "user invalid"})
else:
return JsonResponse({"message": "error"})
Answers:
As the error says, you can not access the serializer.data
and then call save()
.
You should instead user validated_data
:
user_id = serializerdata.validated_data.get('user_id')
Take care that in your debugger watch there is no serializer.data listed.
It will read out the data before serializer.save() is invoked and lead to this confusing behaviour. Took me at least an hour to figure it out.
Error Showing when post data from API
You cannot call `.save()` after accessing `serializer.data`.If you need to access data before committing to the database then inspect 'serializer.validated_data' instead.
My written Code is:
serializerdata = serializers.CreateSerializer(data=request.data)
if serializerdata.is_valid():
user_id = serializerdata.data.get('user_id')
if user_id==2:
serializerdata.save(i_created_by=request.user)
return JsonResponse({"message": "success"})
else:
return JsonResponse({"message": "user invalid"})
else:
return JsonResponse({"message": "error"})
As the error says, you can not access the serializer.data
and then call save()
.
You should instead user validated_data
:
user_id = serializerdata.validated_data.get('user_id')
Take care that in your debugger watch there is no serializer.data listed.
It will read out the data before serializer.save() is invoked and lead to this confusing behaviour. Took me at least an hour to figure it out.