I have some problem. I use routers in Django Rest Framework and I want to test some api methods.
In urls.py:
router = DefaultRouter() router.register(r'my-list', MyViewSet, base_name="my_list") urlpatterns = [ url(r'^api/', include(router.urls, namespace='api'), ), ]
So, in tests.py I want to use something like reverse. Now I use
response = self.client.get('/api/my-list/')
Its a hard coded string, if I use :
response = self.client.get(reverse('api:my_list')
I have an error:
django.core.urlresolvers.NoReverseMatch: Reverse for 'my_list' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
How to fix that?
Thanks!
Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code.
Django REST framework allows you to combine the logic for a set of related views in a single class, called a ViewSet . In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.
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.
REST framework provides an APIView class, which subclasses Django's View class. APIView classes are different from regular View classes in the following ways: Requests passed to the handler methods will be REST framework's Request instances, not Django's HttpRequest instances.
DRF adds suffixes in viewsets for different URLs - list, detail and possibly custom URLs. You can see that in source code and in docs. So in your case the actual reverse should be something like:
reverse('api:my_list-list') # for list URL. e.g. /api/my-list/ reverse('api:my_list-detail') # for detail URL. e.g. /api/my-list/<pk>/
That is why its also probably better to use a resource name as a router base_name
. For example base_name='user'
vs base_name='users_list'
.
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