I try to get details about my authenticated user in my Django app.
For that I created a new resource :
class MyUserResource(ModelResource):
class Meta:
queryset = ReaderUser.objects.all()
resource_name = 'me'
list_allowed_methods = []
detail_allowed_methods = ['get']
authorization = Authorization()
authentication = SessionAuthentication()
excludes = ('password', 'id', 'is_active', 'is_admin', 'last_login')
def apply_authorization_limits(self, request, object_list):
print request.user
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"),
]
When I call my API using /api/me/?format=json
I got the following : More than one resource is found at this URI.
I have also tried without the prepend_urls.
What I don't understand is that the print
statement is never executed in the method apply_authorization_limits
Any hints about what I am doing wrong?
I found two ways to fix my issue:
The first one is two create my own authorization.
In my case, the following:
from tastypie.authorization import Authorization
class SimpleReaderAuthorization(Authorization):
def read_list(self, object_list, bundle):
return object_list.filter(email=bundle.request.user.email)
And I just need to update my resource:
class MyUserResource(ModelResource):
class Meta:
queryset = ReaderUser.objects.all()
resource_name = 'me'
list_allowed_methods = ['get']
authorization = SimpleReaderAuthorization()
authentication = SessionAuthentication()
excludes = ('password', 'id', 'is_active', 'is_admin', 'last_login')
Another simple way is to do the following, as indicated in the documentation.
def get_object_list(self, request):
return super(YourResource, self).get_object_list(request).filter(pk=request.user.pk)
Conclusion: I chose the second one as it is cleaner, and simple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With