Reputation: 1042
I have to write a custom function inside class based view which is like below:
class ExampleView(ListCreateAPIView,
UpdateAPIView,
DestroyAPIView):
queryset = Example.objects.all()
serializer_class = ExampleSerializer
def get(self, request, *args, **kwargs):
/.........some code............./
def random_custom(self, request, *args, **kwargs):
/.........some code............./
Here above I have a random custom function which I need to call from the url. Now I am not sure how to do that. If it was a modelviewset, we can do it easily like this:
path("example/",users.ExampleView.as_view({"get": "random_custom"}),
),
I have done it before in ModelVIewset,ie call custom functions like above but I am not sure how to do that is genericviews like above.
Update
def dispatch(self, request, *args, **kwargs):
if request.method == 'PUT' and kwargs.get('slug'):
return self.custom_function(request,*args,**kwargs)
return super().dispatch(request, *args, **kwargs)
def custom_function(self, request, *args, **kwargs):
instance = self.get_object()
print(instance)
slug = kwargs.get("slug")
print(slug)
print(request.data)
Here I can see that from dispatch, the custom function is called and I can see the print of instance and slug but when I print(request.data) it says the error below:
AttributeError: 'ExampleView' object has no attribute 'data'
I need request.data to perform some logic in the data.
Upvotes: 1
Views: 2092
Reputation: 25220
The code which makes the decision about which method on your APIView-derived class to call is in APIView.dispatch(). You can read the source here.
Here's how it works:
getattr()
to get that method, and call it.This means that there are only two ways to redirect the call from get().
Those are the only two ways to do it.
Upvotes: 2
Reputation: 6378
Have you tried putting random_custom()
into get()
method? It should be executed right after GET
method is initialised by client.
class ExampleView(...):
...
def get(self, request, *args, **kwargs):
self.random_custom()
/.........some code............./
def random_custom(self, request, *args, **kwargs):
/.........some code............./
Upvotes: 2