Custom Permissions Example
A snippet showing how to define custom permissions in DRF.
# permissions.py
from rest_framework.permissions import BasePermission, SAFE_METHODS
class IsOwnerOrReadOnly(BasePermission):
def has_object_permission(self, request, view, obj):
if request.method in SAFE_METHODS:
return True
return getattr(obj, "owner_id", None) == getattr(request.user, "id", None)
# views.py
from rest_framework import viewsets
from .models import Project
from .serializers import ProjectSerializer
from .permissions import IsOwnerOrReadOnly
class ProjectViewSet(viewsets.ModelViewSet):
queryset = Project.objects.all()
serializer_class = ProjectSerializer
permission_classes = [IsOwnerOrReadOnly]
Explanation:
- Read access for everyone; write access restricted to the owner of each object.
- Category Django REST Framework (DRF)
- Total Views 488
- Last Modified 09 June, 2026
- Tags #drf #permissions #api #security
Previous snippet
JWT Authentication Example
Next snippet