Lysandros Nikolaou
Lysandros Nikolaou

Reputation: 338

Django Rest-Framework Serializer: KeyError thrown on field that certainly exists

In the process of building a django-based web application, I came across an error, which I cannot figure how to solve. In the application, my Angular2 front-end sends a post request, which passes to the back-end a JSON object of the following form:

{
    "variable": {
        "name": "testVar"
    }
}

Upon receiving the request the flow of the program goes to the post function, which is defined in the following view, which inherits from django rest-framework's APIView.

class VariableAPIView(APIView):

    permission_classes = (AllowAny, )
    renderer_classes = (VariableJSONRenderer, )
    serializer_class = VariableNameSerializer

    def post(self, request):
        variable = request.data.get('variable', {})
        serializer = self.serializer_class(data=variable)
        serializer.is_valid(raise_exception=True)

        return Response(serializer.data, status=status.HTTP_200_OK)

The serializer's main logic happens in this snippet of code.

class VariableNameSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=255)

    def validate(self, data):
        name = data.get('name', None)

        if name is None:
            raise serializers.ValidationError('A variable name is required.')
      
        try:
            value = server.ReadVariable(name)
        except Exception:
            raise serializers.ValidationError('A variable with this name could not be found')

        return {
            'value': value,
        }

When the django-server receives a request, I get the following exception:

KeyError: 'name'

During handling of the above exception, another exception occurred:

KeyError: "Got KeyError when attempting to get a value for field name on serializer VariableNameSerializer. The serializer field might be named incorrectly and not match any attribute or key on the dict instance. Original exception text was: 'name'."

From what I understand, which I am not sure is right, the meaning of the error is that it cannot find a field, named 'name', which throws a KeyError. However, a 'name' field certainly exists, as you can see in my code. Note that in both errors, the stack traces do not include any of the functions, I have written, which I find pretty odd and being a beginner, I have never come across something like this.

Upvotes: 0

Views: 4547

Answers (1)

Linovia
Linovia

Reputation: 20996

Somehow, you are returning {'value': value} from the validate instead of {'name': value} and this will confuse DRF.

Edit: If you really need value instead of name, you also need to add the source argument to the field:

name = serializers.CharField(source='value', max_length=255)

It may already be translated to value in the validate's data, not dead sure about.

Upvotes: 1

Related Questions