Reactoo
Reactoo

Reputation: 1042

write custom functions inside generic class based view in django rest framework

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

Answers (2)

Nick ODell
Nick ODell

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:

  1. Convert the method name (e.g. GET, POST, OPTIONS) to lowercase. Check that the method name is a valid HTTP method. If not, return an error code.
  2. Check if the object defines a lowercase version of the method name. If not, return an error code.
  3. Use getattr() to get that method, and call it.

This means that there are only two ways to redirect the call from get().

  1. Define get() and make it call random_custom(), as @NixonSparrow describes.
  2. Override the dispatch() method to call something else.

Those are the only two ways to do it.

Upvotes: 2

NixonSparrow
NixonSparrow

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

Related Questions