Skip to content

no way to specify parser_classes for views in a viewset #266

@NANASHI0X74

Description

@NANASHI0X74

Describe the bug
I've got a DocumentViewset that's used to both upload and retrieve files. For the create and update actions, the only sensible parser is MultiPartParser, but all other actions should accept json. So I don't want to set parser_classes on the whole viewset and it looks like there is no such thing as get_parser_classes akin to what can be used for serializers in drf.

There is an annotation in drf that can be used for function based views to override parser_classes, but that won't work for single views in viewsets afaict.

Maybe in this case it would make sense to have an override for parser_classes in extend_schema just like for request/response serializers?

An example:

class DocumentViewSet(viewsets.ModelViewSet):
    permission_classes = (DocumentPermission,)
    queryset = Document.objects.all()
    
    def get_parser_classes(self):
        if self.action == 'create':
            return [MultiPartParser]
        else:
            return [JSONParser]
        
    def get_serializer_class(self):
        if self.action in ('create', 'partial_update', 'update'):
            return DocumentEditSerializer
        elif self.action == 'retrieve':
            return DocumentDetailSerializer
        else:
            return DocumentListSerializer

    def perform_create(self, serializer):
        kwargs = {
            'creator': self.request.user,
            'company': self.request.user.company
        }

        serializer.save(**kwargs)

The resulting schema for the above includes all three of the default parsers:

   operationId: documents_create
      description: ''
      tags:
      - documents
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DocumentEditRequest'
          application/x-www-form-urlencoded:
            schema:
              $ref: '#/components/schemas/DocumentEditRequest'
          multipart/form-data:
            schema:
              $ref: '#/components/schemas/DocumentEditRequest'

Metadata

Metadata

Assignees

No one assigned

    Labels

    fix confirmation pendingissue has been fixed and confirmation from issue reporter is pending

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions