[Fixed]-Override create method in django rest generics CreateAPIView

19👍

The return should be instanceof Response.You can return parent class response, after your stuff

def create(self, request, *args, **kwargs):
    ''' I wanted to do some stuff with serializer.data here '''
    return super(MemberCreate, self).create(request, *args, **kwargs)

or else if you don’t want the parent response, then simply return a Response instance

def create(self, request, *args, **kwargs):
    ''' I wanted to do some stuff with serializer.data here '''
    return Response(status=204)
👤Rajez

6👍

Your view should return a Response object, as said in your AssertionError stacktrace.

In your case, you can try to return an empty Response in order to test your view and your serializer.data

from rest_framework.response import Response
from rest_framework import status


class MemberCreate(generics.CreateAPIView):
    queryset = members.objects.all()
    serializer_class = MemberSerializer
    permission_classes = (permissions.IsAdminUser,)

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(...)
        data = serializer.data

        # ...

        return Response(status=status.HTTP_204_NO_CONTENT)

Typically, you want to return your serializer.validated_data in the end, so this line probably will look like this:

return Response(serializer.validated_data, status=status.HTTP_201_CREATED)

Leave a comment