How to restrict Django REST Framework API endpoints based on user roles?

enter image description here

How can I implement centralized role-based access control for multiple Django REST Framework API endpoints without adding permission checks individually to every API view?

@extend_schema(tags=[schema.LOCATION])
 class LocationViewSet(mixins.ListModelMixin,
                  mixins.CreateModelMixin,
                  mixins.RetrieveModelMixin,
                  mixins.UpdateModelMixin,
                   mixins.DestroyModelMixin,
                  UtilGenericViewSet):
    '''
    LocationList pagination, search, filter, order
    '''
    model = Location
    queryset = Location.objects.all()
    filterset_class = LocationListFilter
    permission_classes = (IsAdminPermission,)

Set it once in settings.py. Every view that doesn't set its own permission_classes uses it, including the router's API root at /base/api/.

REST_FRAMEWORK = {
    "DEFAULT_PERMISSION_CLASSES": ["yourapp.permissions.IsAdminPermission"],
}

Then only the views other roles can use need their own permission_classes, for example permission_classes = (IsAuthenticated,).

Вернуться на верх