I have defined a custom action for a ViewSet
from rest_framework import viewsets class UserViewSet(viewsets.ModelViewSet): @action(methods=['get'], detail=False, permission_classes=[permissions.AllowAny]) def gender(self, request): ....
And the viewset is registered to url in the conventional way
from django.conf.urls import url, include from rest_framework import routers from api import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet, base_name='myuser') urlpatterns = [ url(r'^', include(router.urls)), ]
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
reverse('admin:app_list', kwargs={'app_label': 'auth'}) # '/admin/auth/'
But I tried the following and they don't work
reverse('myuser-list', kwargs={'app_label':'gender'}) # errors out reverse('myuser-list', args=('gender',)) # '/api/users.gender'
In the django-restframework documentation, there is a function called reverse_action
. However, my attempts didn't work
from api.views import UserViewSet a = UserViewSet() a.reverse_action('gender') # error out from django.http import HttpRequest req = HttpRequest() req.method = 'GET' a.reverse_action('gender', request=req) # still error out
What is the proper way to reverse the URL of that action?
the reverse function allows to retrieve url details from url's.py file through the name value provided there. This is the major use of reverse function in Django. The redirect variable is the variable here which will have the reversed value. So the reversed url value will be placed here.
That is, url--> view name . But sometimes, like when redirecting, you need to go in the reverse direction and give Django the name of a view, and Django generates the appropriate url. In other words, view name --> url . That is, reverse() (it's the reverse of the url function).
reverse. Has the same behavior as django. urls. reverse , except that it returns a fully qualified URL, using the request to determine the host and port.
APIView allow us to define functions that match standard HTTP methods like GET, POST, PUT, PATCH, etc. Viewsets allow us to define functions that match to common API object actions like : LIST, CREATE, RETRIEVE, UPDATE, etc.
You can use reverse
just add to viewset's basename action:
reverse('myuser-gender')
See related part of docs.
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