Phoenix
Phoenix

Reputation: 425

How does routers and viewsets configure their urls?

I was reading through a long piece of code. And was stuck at how routers and viewsets automatically configure their URLs. For eg. the views.py file is:

class UserViewSet(viewsets.ModelViewSet):
     authentication_classes = (BasicAuthentication,SessionAuthentication)
     permission_classes = (IsAuthenticated,)
     serializer_class = UserSerializer
     queryset = User.objects.all()

The corresponding urls with router is:

router = DefaultRouter()
router.register(r'users',views.UserViewSet,basename='user')
urlpatterns = router.urls

In the above case, what will be the respective urls for the different actions in viewsets, ie list, create, retrieve, update, partial_update and destroy as mentioned in the djangorestframework documentation on viewsets: http://www.tomchristie.com/rest-framework-2-docs/api-guide/viewsets

Upvotes: 2

Views: 1774

Answers (1)

anjaneyulubatta505
anjaneyulubatta505

Reputation: 11665

When you register the viewset it will generate the following url patterns for above case.

router.register(prefix='users', viewset=views.UserViewSet, basename='user')

It follows the below regex patterns

# Regex for list
r'^{prefix}{trailing_slash}$'
# Regex for detail
r'^{prefix}/{lookup}{trailing_slash}$'

1. List router allows http methods like get to retrieve the resource and post to create the resource.
2. Detail router allows http methods like get to retrieve the data of a a resource,put to update the data of a resource, patch to partial update of resource and delete to delete the resource.

We can also pass a extra keyword argument format while using reverse to generate the dynamic url.

URL patterns for above case

[<URLPattern '^users/$' [name='user-list']>,
 <URLPattern '^users\.(?P<format>[a-z0-9]+)/?$' [name='user-list']>,
 <URLPattern '^users/(?P<pk>[^/.]+)/$' [name='user-detail']>,
 <URLPattern '^users/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$' [name='user-detail']>,
 <URLPattern '^$' [name='api-root']>,
 <URLPattern '^\.(?P<format>[a-z0-9]+)/?$' [name='api-root']>]

Reference: https://github.com/encode/django-rest-framework/blob/master/rest_framework/routers.py

Upvotes: 6

Related Questions