2

http://www.django-rest-framework.org/api-guide/validators/#currentuserdefault

I wants to read default value from userprofile automatically. Right now the offical method support User and DateTime. But I want my customized value. How can I do that?

owner = serializers.HiddenField(
    default=serializers.CurrentUserDefault()
)

2 Answers 2

1

This is my workaround. Copy the example from source code and place it here. Hope near future it has friendly solution.

class CurrentBranchDefault:
    def set_context(self, serializer_field):
        self.user = serializer_field.context['request'].user
        self.branch = self.user.userprofile.selected_branch

    def __call__(self):
        return self.branch

    def __repr__(self):
        return unicode_to_repr('%s()' % self.__class__.__name__)


class StaffOrderSerializer(serializers.ModelSerializer):
    branch = serializers.HiddenField(default=CurrentBranchDefault())
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to calculate one hidden field, using other incoming fields in serializer, than you need to use serializer_field.context['request'].data

This "data" will be validated before "set_context()", so you can use it in safe.

I hope it will help someone else.

class DefineNoteType:
    def set_context(self, serializer_field):
        # setting field "type", calculated by other serializer fields
        data = serializer_field.context['request'].data
        subscriber = data.get('subscriber', None)
        connection = data.get('connection', None)
        if subscriber:
            self.type = 'subscriber_type'
        elif connection:
            self.type = 'connection_type'
        else:
            raise serializers.ValidationError('Custom error.')

    def __call__(self):
        return self.type


class NoteSerializer(serializers.ModelSerializer):
    type = serializers.HiddenField(default=DefineNoteType())

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.