Search code examples
djangotastypie

Return just single object (detail) instead of list


I have a UserResource defined as:

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'user'                                                                                                                       

        # No one is allowed to see all users
        list_allowed_methods = []
        detail_allowed_methods = ['get', 'put', 'patch']

        # Hide staff
        excludes = ('is_staff')

    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(pk=request.user.pk)

    def prepend_urls(self):
        return [ url(r'^(?P<resource_name>%s)/$' % self._meta.resource_name, self.wrap_view('dispatch_detail'), name='api_dispatch_detail') ]

I want URI /user/ to return just current user's details, no list at all. My solution gives "more than one resource found at this uri" error, and indeed dispatch_list is there as well. How can I have /user/ return and handle only current user's details?

Thanks


Solution

  • You should write your own view to wrap around tastypie dispatch_detail :

    class UserResource(ModelResource):
      [...]
    
      def prepend_urls(self):
        return [ url(r'^(?P<resource_name>%s)/$' % self._meta.resource_name, self.wrap_view('current_user'), name='api_current_user') ]
    
      def current_user(self, request, **kwargs):
        user = getattr(request, 'user', None)
        if user and not user.is_anonymous():
            return self.dispatch_detail(request, pk=str(request.user.id))