1

I am building a rest api application with django-rest-framework. I came to the phase where I want to put in place some security. I have a user ressources with the following fields firstname, lastname, dateofbirth (just to say a few). So in my user object they are private fields and fields which can be public. Is there a way to limit the out put fields in the response base on the drf Permission, or if no what would the best practise in genera ?

for example : When the user with the id 1 use : api/user/1 he gets:

{ "id": "1", "firstname":"john", "lastname":"Smith", "dateofbirth":"2015-11-11" }

When the user with the id 2 use : api/user/1 he gets:

{ "id": "1", "firstname":"john", "lastname":"Smith" }

which only says that the dateofbirth is a private fie

1 Answer 1

0

you can do this by overriding the init method in your user serializer like:

class UserSerializer(serializers.ModelSerializer):

    def __init__(self, *args, **kwargs):
        super(UserSerializer, self).__init__(*args, **kwargs)
        if 'pk' in kwargs:
            if not self.context['request'].user.id == kwargs['pk']:
                self.fields.pop('dateofbirth')

    class Meta:
        model = User
        fields = ('id', 'firstname', 'lastname', 'dateofbirth')

you can also refer this question

1
  • 1
    Thank you, sounds like a start. But I think that i rather create 2 serializers, and play with a get_serializer method on the api view. Dec 8, 2015 at 14:45

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.