Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRF ModelViewSet is possible to create custom @action with same url and different methods

I have custom function with @action decorator for routing with two methods GET and DELETE.

Everything works ok if code is in same function and I can run different operations with simple if:

    @action(methods=['GET', 'DELETE'], detail=False, url_path='current', url_name='profile-current',
            permission_classes=[IsAuthenticated])
    def get_current_profile(self, request: Request, **kwargs) -> Response:
        if self.request.method == 'DELETE':
        ...

However I would like to separate the code into two functions still with same route, but different method.

If I separate code into two functions and same url-path and different methods, one of the methods returns method not available error.

Am I missing something here or is not possible to create methods in the way I thought it should work.

like image 957
Uros Avatar asked Nov 05 '25 10:11

Uros


1 Answers

You can try to split the two methods like this

GET method

    @action(
        methods=['GET'],
        detail=False,
        url_path='current',
        url_name='profile-current',
        permission_classes=[IsAuthenticated]
    )
    def get_current_profile(self, request: Request, **kwargs):
        """Get current profile"""

DELETE method


    @get_current_profile.mapping.delete
    def delete_current_profile(self, request, **kwargs):
        """Delete current profile"""

Link here:Doc

like image 82
Aprimus Avatar answered Nov 08 '25 02:11

Aprimus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!