Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get router url name when testing in Django Rest Framework

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!

like image 377
Lev Avatar asked Aug 09 '15 12:08

Lev


People also ask

What is router in Django REST framework?

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.

What is ViewSet in Django REST?

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'.

What is difference between APIView and ViewSet?

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.

What is APIView in Django?

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.


Video Answer


1 Answers

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'.

like image 193
miki725 Avatar answered Sep 21 '22 08:09

miki725