2

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': '[email protected]', 'subject': 'hi'}
s = TestSerializer(data=data)
print(s.is_valid())  # prints False
print(s.errors)     # prints {'from_field': [ErrorDetail(string='This field is required.', code='required')]}

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?

1
  • This has been discussed in Issue #967. It's not possible to remap keys from data to serializer. One option is to convert the field in to_internal_value method for input or to_representation for output Commented Jul 22 at 2:30

1 Answer 1

1

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):
    locals()['from'] = serializers.CharField()
    subject = serializers.CharField()

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.