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.
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 :)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With