Search code examples
pythondjangoresttastypie

Can I disallow delete queries on all instances of a resource in tastypie?


Let's say I have a resource named res, its instances are accessible thourgh the url: .../api/res/<res_id>/

I'd like the clients to be allowed to send delete queries on specific instances (so on the above url), but not to delete all the instances at one time by sending a DELETE on the root url for the resource 'res' (.../api/res/), how can I configure tastypie for that?


Solution

  • You'll have to implement your own authorization as described in the documentation:

    class CustomAuthorization(Authorization):
        def delete_list(self, object_list, bundle):
            raise Unauthorized("You cannot delete multiple objects at once.")
            # or 
            return []
    

    Raising an error will return a HTTP 401 status code, while returning an empty list will return a HTTP 200 status code. Both will not delete any items.

    You can create a subclass of any of the default authorization classes to inherit their behaviour, or you can create your own class and implement all required methods.

    EDIT: As you found out, the easiest way to do this is to specify the list_allowed_methods attribute in the resource's Meta:

    class MyResource(models.ModelResource):
        class Meta:
            list_allowed_methods = ['get', 'post', 'put', 'patch'] # no 'delete'
    

    This will set the allowed methods for requests for multiple objects. It's counterpart detail_allowed_methods will set the allowed methods for single object requests.