0

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

Marin
  • 1,269
  • 15
  • 34

3 Answers3

1

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))
Ponytech
  • 1,567
  • 11
  • 19
  • I realise it has been a long time, but I've just found this and it looks like exactly what I need. However, I find that this code is running *before* the authentication stage, so that it never gets past the `is_anonymous()` check. Any ideas? – Gabriel May 14 '15 at 03:41
0

try:

user = get_object_or_404(User, username=username)
Glyn Jackson
  • 7,820
  • 4
  • 24
  • 52
0

To get the object for the currently logged in user you can pull this from the request object.

user = request.user

or

user = User.Objects.get(username=user.username)

or using the answer from @gyln

user = get_object_or_404(User, username=user.username)

Obviously if you are doing it this way ensure that the user is authenticated at the view.

Using the object.filter function will always return a list even if there is just one result; whereas the objects.get method will only return one result.

Matt Seymour
  • 7,802
  • 6
  • 52
  • 95
  • I know how to get current user, I don't know how to make a tastypie resource that on list returns just a single object instead of a list of objects? – Marin Mar 27 '13 at 12:22