[Answer]-How do I limit the user API response to the current user with Django Tastypie?

1👍

You should define your filter in a new CustomUserAuthorization, check the details of this implementation and check the Tastypie documentation about Authorization.

from tastypie.authorization import Authorization
from tastypie.exceptions import Unauthorized


class CustomUserAuthorization(Authorization):
    def read_list(self, object_list, bundle):
        # This you put your filter
        return object_list.filter(id=bundle.request.user.id)

    def read_detail(self, object_list, bundle):
        # This is to check the current user
        return bundle.obj.id == bundle.request.user.id

    def create_list(self, object_list, bundle):
        raise Unauthorized("Sorry, not allowed.")

    def create_detail(self, object_list, bundle):
        raise Unauthorized("Sorry, not allowed.")

    def update_list(self, object_list, bundle):
        raise Unauthorized("Sorry, not allowed.")

    def update_detail(self, object_list, bundle):
        # Only update your details
        return bundle.obj.id== bundle.request.user.id

    def delete_list(self, object_list, bundle):
        raise Unauthorized("Sorry, no deletes.")

    def delete_detail(self, object_list, bundle):
        raise Unauthorized("Sorry, no deletes.")

Leave a comment