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

storm_buster
  • 7,362
  • 18
  • 53
  • 75

1 Answers1

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

Community
  • 1
  • 1
Anush Devendra
  • 5,285
  • 1
  • 32
  • 24
  • 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. – storm_buster Dec 08 '15 at 14:45