override create method in django rest generics CreateAPIView
Asked Answered
C

2

17

My views.py of django app is as below,

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

    def create(self, serializer):
        ''' I wanted to do some stuff with serializer.data here '''
        pass 

Here in the above if I override the create function the return is failing with following error, Even If I don't do any thing and just write pass it is failing ,

AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
Craniate answered 31/8, 2017 at 12:48 Comment(0)
R
20

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)
Rameriz answered 31/8, 2017 at 12:51 Comment(1)
Here is the DRF default implementation of the create() [github.com/encode/django-rest-framework/blob/master/… It may help if you need it.Preposterous
P
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)
Periostitis answered 31/8, 2017 at 12:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.