djangodjango-rest-frameworkdjango-permissions

Dependant permissions in django rest framework


I have a query -

Suppose I have a notebooks (Physics,Chemistry,Math,...) and I want to put note in these notebooks by implementing some permissions -

  1. If I have permissions to view notebooks and I must be able to see all/some note books in drop down

  2. I should be able to add/delete/view note inside any notebook if I am allowed to access that notebook and allowed to add/delete/view note inside that notebook

What could be best approach to implement this situation best

I walk around stack overflow but did not find any answer regarding it


Solution

  • You can override the get_permissions class in your view depending on the action being performed, you can also add in your own permission, here is an example working with ModeViewSet.

    def get_permissions(self):
        if self.action in ['create', 'list', 'retrieve']:
            # Add or View records if you are logged in
            return (permissions.IsAuthenticated(),)
        else:
            # Delete or update records if you are logged in and added the record
            return (permissions.IsAuthenticated(), IsOwner(),)
    

    IsOwner is coming from a custom permission class in permissions.py as below:

    from rest_framework import permissions
    
    
    class IsOwner(permissions.BasePermission):
    
        def has_object_permission(self, request, view, obj):
            return obj.user == request.user
    

    This example custom class checks if the logged in user is the user that created the record assuming there is a user pk in the notebook model.

    Also in your user model, you can set is_staff=True and user permissions.IsAdminUser for users allowed to view the records or create a custom permission class to be based on some user type.