how to reverse the URL of a ViewSet's custom action in django restframework how to reverse the URL of a ViewSet's custom action in django restframework django django

how to reverse the URL of a ViewSet's custom action in django restframework


You can use reverse just add to viewset's basename action:

reverse('myuser-gender') 

See related part of docs.


You can print all reversible url names of a given router at startup with the get_urls() method

In urls.py after the last item is registered to the router = DefaultRouter() variable, you can add:

#router = routers.DefaultRouter()#router.register(r'users', UserViewSet)#...import pprintpprint.pprint(router.get_urls())

The next time your app is initialized it will print to stdout something like

[<RegexURLPattern user-list ^users/$>, <RegexURLPattern user-list ^users\.(?P<format>[a-z0-9]+)/?$>, <RegexURLPattern user-detail ^users/(?P<pk>[^/.]+)/$>, <RegexURLPattern user-detail ^users/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$>,         #...]

where 'user-list' and 'user-detail' are the names that can be given to reverse(...)


Based on DRF Doc.

from rest_framework import routersrouter = routers.DefaultRouter()view = UserViewSet()view.basename = router.get_default_basename(UserViewSet)view.request = None

or you can set request if you want.

view.request = req

In the end, you can get a reverse action URL and use it.

url = view.reverse_action('gender', args=[])