Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Tastypie - Resource with object details only

In Django with Tastypie, is there a way to configure a resource such that it only shows object details?

I want to have a url /user which returns the details of the authenticated user, as opposed to a list containing a single user object. I don't want to have to use /users/<id> to get the details of a user.

Here's the relevant portion of my code:

from django.contrib.auth.models import User
from tastypie.resources import ModelResource

class UserResource(ModelResource):

    class Meta:
        queryset        = User.objects.all()
        resource_name   = 'user'
        allowed_methods = ['get', 'put']
        serializer      = SERIALIZER      # Assume those are defined...
        authentication  = AUTHENTICATION  # "
        authorization   = AUTHORIZATION   # "

    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(pk=request.user.pk)
like image 438
surj Avatar asked Jan 19 '26 12:01

surj


1 Answers

I was able to do this by using a combination of the following resource methods

  • override_urls
  • apply_authorization_limits

Example user resource

#Django
from django.contrib.auth.models import User
from django.conf.urls import url

#Tasty
from tastypie.resources import ModelResource

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

        #Disallow list operations
        list_allowed_methods = []
        detail_allowed_methods = ['get', 'put', 'patch']

        #Exclude some fields
        excludes = ('first_name', 'is_active', 'is_staff', 'is_superuser', 'last_name', 'password',)

    #Apply filter for the requesting user
    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(pk=request.user.pk)

    #Override urls such that GET:users/ is actually the user detail endpoint
    def override_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
        ]

Using something other than the primary key for getting the details of a resource is explained in more detail in the Tastypie Cookbook

like image 183
jpennell Avatar answered Jan 21 '26 02:01

jpennell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!