假设我有一个名为UserViewset
的视图集,并且我已将IsAuthenticated
权限分配给UserViewset
视图集。现在,我想创建一个普通方法(不是动作方法),我想给那个方法分配另一个权限,也就是IsAdminUser
,我该怎么做呢?
from rest_framework.viewsets import GenericViewSet
from rest_framework.permissions import IsAuthenticated, IsAdminUser
class UserViewset(GenericViewSet):
permission_classes = (IsAuthenticated,) # THIS IS THE DEFAULT PERMISSION I HAVE SET FOR THIS VIEWSET WHICH WILL APPLY TO ALL METHODS OR ACTION METHODS
def create(self, *args, **kwargs): # THIS IS MY CUSTOM METHOD
permission_classes = (IsAuthenticated, IsAdminUser) # I WANT SOMETHONG LIKE THIS, BUT IT DOES NOT WORK
.
.
.
可以重写get_permission类
def get_permissions(self):
# check the action and return the permission class accordingly
if self.action == 'create':
return [IsAdminUser(),]
return [IsAuthenticated(), ]