Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add permissions in Django Rest Framework for specific requests

I am creating a class based api for a documentation app, but I want to add specific permissions to the post and patch definitions in my APIView. For example,

class DocumentList(APIView):

    def get(self,request,format=None):
         ... blah

    def post(self,request,format=None):
        only allow administrators to create new documents 
        ... blah
like image 695
user1876508 Avatar asked Jun 19 '13 20:06

user1876508


1 Answers

By default permissions are unrestricted. In your settings.py you can specify a different set of defaults to where users have to be authenticated and have the correct Django model permission. You will need to specify a model attribute on your view class for the DjangoModelPermissions to take effect.

# settings.py
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
        'rest_framework.permissions.DjangoModelPermissions'
    )
}

# views.py
class DocumentList(APIView):
    model = Document
    ...

The DjangoModelPermissions permission map can be found in the source.

  • GET, OPTIONS and HEAD don't require a permission but since we specified IsAuthenticated we're still requiring that
  • POST maps to add
  • PUT and PATCH map to change
  • DELETE maps to delete
like image 71
Scott Woodall Avatar answered Oct 14 '22 07:10

Scott Woodall