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?
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({...})
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):
.....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With