slqq
slqq

Reputation: 265

Django Rest Framework url_pattern of @action

I need to pass instance id after last / of my @action name method, and I seriously have no idea how...

I have a UserViewSet, which url to access list is : /users/, then i have action called favorite_posts, which is detail=False because I'm filtering by current logged user, and the action refer to user posts, I wanna be able to pass the post_id like /users/favorite_posts/post_id/, because in this case it's more friendly to me than /users/1/favorite_posts/ which I could obtain setting detail=True.

Is there any way to do that?

Upvotes: 7

Views: 11904

Answers (3)

Steve Galili
Steve Galili

Reputation: 1

This only works with r because its regex use url_path=r'favorite_posts/(?P<user_id>\d+)', url_name='favorite-posts'

Upvotes: 0

Reza Torkaman Ahmadi
Reza Torkaman Ahmadi

Reputation: 3038

You can use it like this:

@action(methods=['get'], detail=False, url_path='req/(?P<post_id>\d+)')

and get post_id in your method like this: kwargs.get('post_id') or just pass post_id directly to your method.

@action(methods=['get'], detail=False, url_path='req/(?P<post_id>\d+)')
def get_post(request, post_id):
     .....

Upvotes: 5

kaveh
kaveh

Reputation: 2146

You can include parameters in your url pattern and have user_id passed to your method like this:

@action(methods=['post'], detail=False, url_path='favorite_posts/(?P<user_id>\d+)', url_name='favorite-posts')
def get_favorite_post(self, request, user_id):
    # Do something
    return Response({...})

Upvotes: 14

Related Questions