source is not working for deserializing POST data in django rest framework

source is not working for deserializing POST data in django rest framework
typescript
Ethan Jackson

The following example doesn't work as expected, and returns a validation error. Why is that?

from rest_framework import serializers class TestSerializer(serializers.Serializer): from_field = serializers.CharField(source='from') subject = serializers.CharField() data = {'from': '

What I am looking to do is map an external POST data which has the protected word from, and validate the input with the serializer. If the above is not expected to work, what alternatives exist?

Answer

You have specified it the other way around. You here convert data into cleaned data, so you inject data as from_field, and you get in the cleaned data as from, and if you use TestSializer(cleaned_data), it will give you a dictionary with from_field.

What I am looking to do is map an external POST data which has the protected word from.

You can essentially inject a field with a reserved name, through:

class TestSerializer(serializers.Serializer):

or better:

TestSerializer = type( 'TestSerializer', (serializers.Serializer,) {'from': serializers.CharField(), 'subject': serializer.CharField()} )

whether that is a good idea is of course open for discussion.

Related Articles