Shashwat
Shashwat

Reputation: 449

how to override the .create() method inside a generic view (example: ListCreateAPIView) in django-rest-framework?

I wanted to override the create method in class-based view which implements the ListCreateAPIView , not generally while overriding methods like the get_queryset(self) method, the requests, the url **kwargs are accessed from self, but I wanted to override the .create() method of the CreateModelMixin, so I took a look at the code to find the signature as create(self, request, *args, **kwargs) what does django pass in the **kwargs, *args of this function? are these url **kwargs by any chance? How do I go about overriding the create method in the generic view asthe request in any function of the generic view is accessed from the self but the signature of the create function explicitly requires a request argument.

Upvotes: 4

Views: 10603

Answers (2)

Asad Manzoor
Asad Manzoor

Reputation: 1465

from rest_framework import generics

from tasks.models import Task
from tasks.serializers import TaskSerializer


class TaskList(generics.ListCreateAPIView):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer

    def create(self, request, *args,**kwargs):
        # your implementation
        return Response(response)

Upvotes: 1

mrehan
mrehan

Reputation: 1182

Following is DRF ListCreateAPIView, as you can see *args, **kwargs are directly passing down from standard post method:

class ListCreateAPIView(mixins.ListModelMixin,
                    mixins.CreateModelMixin,
                    GenericAPIView):
    """
    Concrete view for listing a queryset or creating a model instance.
    """
    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

Now, talking about overriding create from CreateModelMixin, you can simply override it as:

from rest_framework import generics

class YourWonderfulView(generics.ListCreateAPIView):

    queryset = YourModelClass.objects.all()
    serializer_class = YourSerializer

    def create(self, request, *args, **kwargs): # don't need to `self.request` since `request` is available as a parameter.

        # your custom implementation goes here

        return Response(response) # `response` is your custom response – e.g. dict, list, list of dicts etc

Hope it helps :)

Upvotes: 13

Related Questions