Uros
Uros

Reputation: 61

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.

Upvotes: 4

Views: 2359

Answers (2)

LylaLee
LylaLee

Reputation: 1

You can try to separate the two methods within the function like this:

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

Upvotes: 0

Aprimus
Aprimus

Reputation: 1551

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

Upvotes: 8

Related Questions