Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 956
Shashwat Avatar asked Dec 23 '22 06:12

Shashwat


2 Answers

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 :)

like image 110
mrehan Avatar answered Dec 25 '22 18:12

mrehan


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)
like image 36
Asad Manzoor Avatar answered Dec 25 '22 20:12

Asad Manzoor