Last modified: Oct 03, 2023 By Alexander Williams

Django Rest Framework IsAdminUser Permission Examples

Example 1: Using IsAdminUser Permission for a ViewSet


from rest_framework import viewsets, permissions

class MyModelViewSet(viewsets.ModelViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer
    
    # Apply the IsAdminUser permission class to this view
    permission_classes = [permissions.IsAdminUser]

Example 2: Using IsAdminUser Permission for a Function-Based View


from rest_framework import permissions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response

# Apply the IsAdminUser permission class to this view function
@api_view(['GET'])
@permission_classes([permissions.IsAdminUser])
def admin_only_view(request):
    return Response({"message": "This view can only be accessed by admin users."})

Example 3: Using IsAdminUser Permission Globally


# settings.py

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAdminUser',
    ],
}

Example 4: Customizing Access Denied Message


# settings.py

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAdminUser',
    ],
    'DEFAULT_PERMISSION_DENIED_HANDLER': 'myapp.permissions.custom_permission_denied',
}

# myapp/permissions.py

from rest_framework.exceptions import PermissionDenied
from rest_framework.response import Response

# Define a custom permission denied handler with a customized message
def custom_permission_denied(request, message=None):
    raise PermissionDenied(detail=message or "You do not have permission to perform this action.")