Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django-rest-framework: add additional permission in ViewSet update method

I have the following code:

class UsersViewSet(viewsets.ModelViewSet):
    model = Users
    permission_classes = (IsAuthenticated,)

    def update(self, request, *args, **kwargs):
        return super(UsersViewSet, self).update(request, *args, **kwargs)

The question is:

  • how can I add additional Permission only for update method? (need to get isAuthenticated + Permission)
  • overwrite permissions only for update method? (need to get only Permission without isAuthenticated) other methods in viewset should have IsAuthenticated permission

Can I make it with decorator?Or anything else?

Wanna get something like that:

@permission_classes((IsAuthenticated, AdditionalPermission ))
def update:
    pass

But if i write this code the second permission is not checked through request

like image 944
Ellochka Cannibal Avatar asked Aug 13 '14 10:08

Ellochka Cannibal


People also ask

What is difference between ViewSet and ModelViewSet?

It is more rigid than a generic APIView but it takes away from you some boilerplate/manual config that you would have to repeat again and again in most cases. One step further is the ModelViewSet , which is an extension of the ViewSet for when you are working with Django models.

Should I use APIView or ViewSet?

APIView and ViewSet all have their right use cases. But most of the time, if you are only doing CRUD on resources, you can directly use ViewSets to respect the DRY principle. But if you are looking for more complex features, you can go low-level because after all, viewsets are also a subclass of APIView .

How do I update user details in Django REST framework?

Open auth/urls.py and add update profile endpoint. we should send a PUT request to API for checking update profile endpoint. We must add username, first_name, last_name and email. If fields passed validations, user profile will be changed.

What is ViewSet in Django REST framework?

A ViewSet class is simply a type of class-based View, that does not provide any method handlers such as . get() or . post() , and instead provides actions such as . list() and . create() .


2 Answers

LATER EDIT

As it seems that DRF decorators don't really work (at least not for me), this is the best solution I could come up with:

def get_permissions(self):
    # Your logic should be all here
    if self.request.method == 'GET':
        self.permission_classes = [DummyPermission, ]
    else:
        self.permission_classes = [IsAuthenticated, ]

    return super(UsersViewSet, self).get_permissions()

This actually works for both cases that you asked, but requires a bit more work. However, I've tested it and it does the job.

ORIGINAL ANSWER BELOW

There is a small mistake in the docs, you should be sending a list to the decorator (not a tuple). So it should be like this:

@permission_classes([IsAuthenticated, AdditionalPermission, ])
def update:
    pass

To answer your questions:

how can I add additional Permission only for update method?

First of all, you should know that DRF first checks for global permissions (those from the settings file), then for view permissions (declared in permission_classes -- if these exist, they will override global permissions) and only after that for method permissions (declared with the decorator @permission_classes). So another way to do the above is like this:

@permission_classes([AdditionalPermission, ])
def update:
    pass

Since ISAuthenticated is already set on the entire view, it will always be checked BEFORE any other permission.

overwrite permissions only for update method?

Well, this is hard(er), but not impossible. You can:

  • set the permissions for each method and remove it from the class
  • modify your AdditionalPermission class so that it also checks for user authentication if the method is not update.

Good luck.

like image 92
AdelaN Avatar answered Oct 02 '22 23:10

AdelaN


You can also specify permissions for specific methods in the get_permissions() method:

class MyViewSet(viewsets.ModelViewSet):

    def get_permissions(self):
        if self.action in ('update', 'other_viewset_method'):
            self.permission_classes = [permissions.CustomPermissions,]
        return super(self.__class__, self).get_permissions()
like image 21
boudah Avatar answered Oct 02 '22 23:10

boudah