Routing to extra methods on a ViewSet

4,455 views
Skip to first unread message

Roger Boardman

unread,
Oct 15, 2013, 8:22:16 AM10/15/13
to django-res...@googlegroups.com
Hi,

I'm trying to understand how i can add an additional method to a ViewSet that is routable against a list endpoint rather than a single instance endpoint.

I understand i can mark additional methods on the ViewSet with the @action and @link decorators.  From the docs the following example is given

class UserViewSet(viewsets.ModelViewSet):
    """
    A viewset that provides the standard actions
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer

    @action()
    def set_password(self, request, pk=None):
        user = self.get_object()
        serializer = PasswordSerializer(data=request.DATA)
        if serializer.is_valid():
            user.set_password(serializer.data['password'])
            user.save()
            return Response({'status': 'password set'})
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
This would result in the action then being available at a url similar to

^users/{pk}/set_password/$


Now say i want to add a 'username_available' method to the ViewSet where i can check availability of a given username.  Logically the route for this should appear under the list endpoint and not an instance endpoint.

i.e.

^users/username_available/$

rather than 

^users/{pk}/username_available/$

as would be the case when using the @link or @action decorators.

What would be the best way to achieve this?

Thanks
Roger.










Aristomenis Pikeas

unread,
Nov 7, 2013, 7:52:38 AM11/7/13
to django-res...@googlegroups.com
Bump. Is there an official DRF way to do this?

Carlton Gibson

unread,
Nov 7, 2013, 8:13:30 AM11/7/13
to django-res...@googlegroups.com
Hi Aristomenis, 

I think you may need to route the method by hand, i.e. The Old-Fashioned Way™. 

First pull the method out as a separate view: 

   set_password_view = UserViewSet.as_view({'post': 'set_password'})

(or such)

Then assign your URL:

   url(r'^users/username_available/$', set_password_view, name-=...)

(Or such)


Hopefully that helps? 

Regards,

Carlton


--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Reply all
Reply to author
Forward
0 new messages