Skip to content

Improve error handling when accessing request.data in get_serializer_class #325

Open
@DeadLemon

Description

@DeadLemon

Hi there!
I'm trying to specify different serializers depend on user type or request data.

class UserViewSet(serializers.ModelSerializer):
    ...
    def get_serializer_class(self):
        serializers_map = {}
        if self.request.user.is_authenticated:
            pass
        else:
            serializers_map.update({'create': serializers.CreateSerializerForAnonymousUser})
        return serializers_map.get(view.action, None)

So, I get an error:
[{'detail': 'JSON parse error - Expecting value: line 1 column 1 (char 0)', 'source': {'pointer': '/data'}, 'status': '400'}]
Here is my test code:

class UserEndpointCreateTest(APITestCase):
    def setUp(self):
        self.path = reverse('user-list')
        self.data = {
            'data': {
                'type': format_resource_type('user'),
                'attributes': {
                    'phone_number': '+79000000001',
                    'password': 'password'
                }
            }
        }

    def test_anonymous_user(self):
        response = self.client.post(reverse('user-list'), json.dumps(self.data), content_type='application/vnd.api+json')
        print(response.data)

Also, I tried this code with default rest_framework serializer, renderers and parsers - it works properly. Note that this problem exposes only when I'm trying to access request.user or request.data

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions