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
Yes you can by adding annotation See this link for more information there are examples:
https://docs.djangoproject.com/en/1.6/topics/auth/default/#django.contrib.auth.decorators.permission_required
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:
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:
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:
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:
Good luck.
@permission_classes didn't work for class based view. And I tried @detail_route(permission_classes=(permissions.CustomPermissions,)) for update view function, still not work.
so, my solution is:
Have a try. my drf is v3.1.1
You can also specify permissions for specific methods in the get_permissions() method: