Reputation: 1303
I extend django views like this
class UserList(APIView):
def post(self, etc, etc):
return Response(serializer.data, status=status=status.HTTP_201_CREATED)
Now I want to call other methods if the post response is a success. How can I do it in the same class UserList? (or do you have a better idea?)
Upvotes: 0
Views: 1100
Reputation: 47866
You can create a PostSuccessMixin
class which will override the dispatch()
method. Then, we will inherit this mixin in our view and call the super's dispatch()
. On calling that, we will get the proper DRF response. Then we can check if the status code of the response was 201. If it was 201, then we call the other methods here. In the end, we return the original DRF response recieved initially after calling the super's dispatch()
.
class PostSuccessMixin(object):
def dispatch(self, request, *args, **kwargs):
response = super(PostSuccessMixin, self).dispatch(request, *args, **kwargs)
if response.status_code == 201:
...
call other methods
...
return response
In your views, inherit this mixin. views.py
class UserList(PostSuccessMixin, APIView):
def post(self, etc, etc):
return Response(serializer.data, status=status=status.HTTP_201_CREATED)
Upvotes: 2