I have defined a custom action for a ViewSet
JavaScript
x
7
1
from rest_framework import viewsets
2
3
class UserViewSet(viewsets.ModelViewSet):
4
@action(methods=['get'], detail=False, permission_classes=[permissions.AllowAny])
5
def gender(self, request):
6
.
7
And the viewset is registered to url in the conventional way
JavaScript
1
13
13
1
from django.conf.urls import url, include
2
3
from rest_framework import routers
4
from api import views
5
6
7
router = routers.DefaultRouter()
8
router.register(r'users', views.UserViewSet, base_name='myuser')
9
10
urlpatterns = [
11
url(r'^', include(router.urls)),
12
]
13
The URL /api/users/gender/
works. But I don’t know how to get it using reverse
in unit test. (I can surely hard code this URL, but it’ll be nice to get it from code)
According to the django documentation, the following code should work
JavaScript
1
3
1
reverse('admin:app_list', kwargs={'app_label': 'auth'})
2
# '/admin/auth/'
3
But I tried the following and they don’t work
JavaScript
1
5
1
reverse('myuser-list', kwargs={'app_label':'gender'})
2
# errors out
3
reverse('myuser-list', args=('gender',))
4
# '/api/users.gender'
5
In the django-restframework documentation, there is a function called reverse_action
. However, my attempts didn’t work
JavaScript
1
8
1
from api.views import UserViewSet
2
a = UserViewSet()
3
a.reverse_action('gender') # error out
4
from django.http import HttpRequest
5
req = HttpRequest()
6
req.method = 'GET'
7
a.reverse_action('gender', request=req) # still error out
8
What is the proper way to reverse the URL of that action?
Advertisement
Answer
You can use reverse
just add to viewset’s basename action:
JavaScript
1
2
1
reverse('myuser-gender')
2
See related part of docs.