Search code examples
pythondjango-rest-frameworkdjoser

DRF: Djoser override custom user serializer


Previously I had been working with the back-end, but after few months of not coding, I'm now not really comfortable with the code I have now. So I use Djoser and I have this in my project settings.py file

  ...
    'SERIALIZERS': {
            'user_create': 'backend.accounts.serializers.UserCreateSerializer',
            'user': 'backend.accounts.serializers.UserCreateSerializer',
            'user_delete': 'djoser.serializers.UserDeleteSerializer',
    }
  ...

This should override the default Djoser serializer, but as I can see it does nothing.

/auth/users/me/ - Returns this

{
    "email": "[email protected]",
    "id": 1,
    "username": "test"
}

but I have this as my serializer inside backend/accounts/serializers

class UserCreateSerializer(UserCreateSerializer):
    delete_request = DeleteUserSerializer(read_only=True)

    class Meta(UserCreateSerializer.Meta):
        model = User
        fields = (
            'id',
            'email',
            'username',
            'password',
            'delete_request',
        )

Why does it not override?


Solution

  • /users/me/ endpoint is handled by current_user key in djoser serializers dict, so you should add it:

    'SERIALIZERS': {
        # [...]
        'current_user': 'backend.accounts.serializers.UserSerializer',
        # [...]
    }
    

    You can have more information about djoser serializers on the documentation.

    They say:

    Key 'user' is used for general users whereas 'current_user' lets you set serializer for special /users/me endpoint. They both default to the same serializer though.

    And by the way I think you should create a serializer inheriting from djoser.serializers.UserSerializer and not from djoser.serializers.UserCreateSerializer for user and cuttent_user keys.